diff --git a/src/it/reyboz/bustorino/adapters/GPSLocationAdapter.java b/src/it/reyboz/bustorino/adapters/GPSLocationAdapter.java deleted file mode 100644 index 1b0f8ce..0000000 --- a/src/it/reyboz/bustorino/adapters/GPSLocationAdapter.java +++ /dev/null @@ -1,90 +0,0 @@ -package it.reyboz.bustorino.adapters; - -import android.content.Context; -import android.database.Cursor; -import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.os.Bundle; -import android.support.v4.app.LoaderManager; -import android.util.Log; - -import java.util.ArrayList; - -public class GPSLocationAdapter implements LocationListener { - private Context con; - private LocationManager locMan; - public static final String DEBUG_TAG = "BUSTO LocAdapter"; - private final String BUNDLE_LOCATION = "location"; - - private int oldLocStatus = -2; - private float maxAccuracy; - private ArrayList loadersIDsToNotify; - - LoaderManager.LoaderCallbacks callbacks; - - public GPSLocationAdapter(Context con,float maxAccuracyinMeters) { - this.con = con; - this.maxAccuracy = maxAccuracyinMeters; - locMan = (LocationManager) con.getSystemService(Context.LOCATION_SERVICE); - } - - - boolean startRequestingPosition(){ - try { - locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this); - return true; - } catch (SecurityException exc){ - exc.printStackTrace(); - return false; - } - } - - public float getMaxAccuracy() { - return maxAccuracy; - } - - public void setMaxAccuracy(float maxAccuracy) { - this.maxAccuracy = maxAccuracy; - } - - public void addLoaderToPing(int loaderID){ - if(!loadersIDsToNotify.contains(loaderID)){ - loadersIDsToNotify.add(loaderID); - } else Log.d(DEBUG_TAG,"Requested to add loader "+loaderID+" which is already there"); - } - public void removeLoaderToPing(int loaderID){ - if(loadersIDsToNotify.contains(loaderID)){ - loadersIDsToNotify.remove(loaderID); - } else Log.d(DEBUG_TAG,"Requested to remove loader "+loaderID+" which is not present"); - } - - @Override - public void onLocationChanged(Location location) { - Log.d("GPSLocationListener","found location:\nlat: "+location.getLatitude()+" lon: "+location.getLongitude()+"\naccuracy: "+location.getAccuracy()); - - float accu = location.getAccuracy(); - if(accu< maxAccuracy){ - Bundle msgBundle = new Bundle(); - msgBundle.putParcelable(BUNDLE_LOCATION,location); - - } - - } - - @Override - public void onStatusChanged(String provider, int status, Bundle extras) { - - } - - @Override - public void onProviderEnabled(String provider) { - startRequestingPosition(); - } - - @Override - public void onProviderDisabled(String provider) { - locMan.removeUpdates(this); - } - -} diff --git a/src/it/reyboz/bustorino/backend/DBStatusManager.java b/src/it/reyboz/bustorino/backend/DBStatusManager.java index 0a92df5..6eed4b5 100644 --- a/src/it/reyboz/bustorino/backend/DBStatusManager.java +++ b/src/it/reyboz/bustorino/backend/DBStatusManager.java @@ -1,91 +1,90 @@ /* BusTO - Backend components Copyright (C) 2019 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import it.reyboz.bustorino.R; /** * Class to handle app status modifications, e.g. database is being updated or not */ public class DBStatusManager { private static String PREFERENCES_NAME;// = "it.reyboz.bustorino.statusPreferences"; private String DB_UPDATING; private SharedPreferences preferences; - //private ArrayList prefListeners; - //private static DBStatusManager classinstance; + private SharedPreferences.OnSharedPreferenceChangeListener prefListener; private OnDBUpdateStatusChangeListener dbUpdateListener; public DBStatusManager(Context context, OnDBUpdateStatusChangeListener listener) { Context thecon = context.getApplicationContext(); this.preferences = thecon.getSharedPreferences(context.getString(R.string.mainSharedPreferences),Context.MODE_PRIVATE); DB_UPDATING = context.getString(R.string.databaseUpdatingPref); PREFERENCES_NAME = context.getString(R.string.mainSharedPreferences); dbUpdateListener = listener; //this.prefListeners = new ArrayList<>(); prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d("BUSTO-PrefListener", "Changed key " + key + " in the sharedPref"); if (key.equals(DB_UPDATING)) { dbUpdateListener.onDBStatusChanged(sharedPreferences.getBoolean(DB_UPDATING, dbUpdateListener.defaultStatusValue())); } } }; } public boolean isDBUpdating(boolean defaultvalue){ if (preferences == null) //preferences = thecon.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE); { //This should NOT HAPPEN Log.e("BUSTO_Pref","Preference reference is null"); return false; } else { return preferences.getBoolean(DB_UPDATING,defaultvalue); } } public void registerListener(){ if(prefListener!=null) preferences.registerOnSharedPreferenceChangeListener(prefListener); } public void unregisterListener(){ if(prefListener!=null) preferences.unregisterOnSharedPreferenceChangeListener(prefListener); } public void setDbUpdating(boolean value){ final SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(DB_UPDATING,value); editor.apply(); } public interface OnDBUpdateStatusChangeListener { void onDBStatusChanged(boolean updating); boolean defaultStatusValue(); } } diff --git a/src/it/reyboz/bustorino/backend/Route.java b/src/it/reyboz/bustorino/backend/Route.java index 05b9b7f..9aae920 100644 --- a/src/it/reyboz/bustorino/backend/Route.java +++ b/src/it/reyboz/bustorino/backend/Route.java @@ -1,288 +1,288 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; public class Route implements Comparable { final static int[] reduced_week = {Calendar.MONDAY,Calendar.TUESDAY,Calendar.WEDNESDAY,Calendar.THURSDAY,Calendar.FRIDAY}; final static int[] feriali = {Calendar.MONDAY,Calendar.TUESDAY,Calendar.WEDNESDAY,Calendar.THURSDAY,Calendar.FRIDAY,Calendar.SATURDAY}; final static int[] weekend = {Calendar.SUNDAY,Calendar.SATURDAY}; - final static int BRANCHID_MISSING = -1; + private final static int BRANCHID_MISSING = -1; public final String name; public String destinazione; public final List passaggi; public final Type type; public String description; //ordered list of stops, from beginning to end of line private List stopsList = null; public int branchid = BRANCHID_MISSING; public int[] serviceDays ={}; //0=>feriale, 1=>festivo -2=>unknown public FestiveInfo festivo = FestiveInfo.UNKNOWN; public enum Type { // "long distance" sono gli extraurbani. BUS(1), LONG_DISTANCE_BUS(2), METRO(3), RAILWAY(4), TRAM(5); //TODO: decide to give some special parameter to each field private int code; Type(int code){ this.code = code; } public int getCode(){ return this.code; } @Nullable public static Type fromCode(int i){ switch (i){ case 1: return BUS; case 2: return LONG_DISTANCE_BUS; case 3: return METRO; case 4: return RAILWAY; case 5: return TRAM; default: return null; } } } public enum FestiveInfo{ FESTIVO(1),FERIALE(0),UNKNOWN(-2); private int code; FestiveInfo(int code){ this.code = code; } public int getCode() { return code; } public static FestiveInfo fromCode(int i){ switch (i){ case -2: return UNKNOWN; case 0: return FERIALE; case 1: return FESTIVO; default: return UNKNOWN; } } } /** * Constructor. * * @param name route ID * @param destinazione terminus\end of line * @param type bus, long distance bus, underground, and so on * @param passaggi timetable, a good choice is an ArrayList of size 6 * @see Palina Palina.addRoute() method */ public Route(String name, String destinazione, Type type, List passaggi) { this.name = name; this.destinazione = destinazione; this.passaggi = passaggi; this.type = type; this.description = null; } /** * Constructor used by the new Api * @param name stop Name * @param t optional type * @param description line rough description */ public Route(String name,Type t,String description){ this.name = name; this.type = t; this.passaggi = new ArrayList<>(); this.destinazione = null; this.description = description; } /** * Exactly what it says on the tin. * * @return times from the timetable */ public List getPassaggi() { return this.passaggi; } public void setStopsList(List stopsList) { this.stopsList = Collections.unmodifiableList(stopsList); } public List getStopsList(){ return this.stopsList; } /** * Adds a time (passaggio) to the timetable for this route * * @param TimeGTT time in GTT format (e.g. "11:22*") */ public void addPassaggio(String TimeGTT) { this.passaggi.add(new Passaggio(TimeGTT)); } public static String getPassageString(String input,boolean realtime){ String time = input.trim(); if(time.contains("*")){ if(realtime) return time; else return time.substring(0,time.length()-1); } else{ if(realtime) return time.concat("*"); else return time; } } @Override public int compareTo(@NonNull Route other) { int res; int thisAsInt, otherAsInt; // sorting by numbers alone yields a far more "natural" result (36N goes before 2024, 95B next to 95, and the like) thisAsInt = networkTools.failsafeParseInt(this.name.replaceAll("[^0-9]", "")); otherAsInt = networkTools.failsafeParseInt(other.name.replaceAll("[^0-9]", "")); // compare. // numeric route IDs (names) if(thisAsInt != 0 && otherAsInt != 0) { res = thisAsInt - otherAsInt; if(res != 0) { return res; } } else { // non-numeric res = this.name.compareTo(other.name); if (res != 0) { return res; } } // try comparing their destination if(this.destinazione!=null){ res = this.destinazione.compareTo(other.destinazione); if(res != 0) { return res; } } //compare the lines if(this.stopsList!=null && other.stopsList!=null){ int d = this.stopsList.size()-other.stopsList.size(); if(d!=0) return d; else { //the two have the same number of stops } } // probably useless, but... last attempt. if(this.type != other.type) { // ordinal() is evil or whatever, who cares. return this.type.ordinal() - other.type.ordinal(); } return 0; } public boolean isBranchIdValid(){ return branchid!=BRANCHID_MISSING; } @Override public boolean equals(Object obj) { if(obj instanceof Route){ Route r = (Route) obj; boolean result = false; if(this.name.equals(r.name) && this.branchid == r.branchid){ if(this.stopsList!=null && r.stopsList!=null){ int d = this.stopsList.size()-r.stopsList.size(); if(d!=0) { result = false; } else { result = true; for(int j=0; j. */ package it.reyboz.bustorino.fragments; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.location.LocationProvider; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.preference.PreferenceManager; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import it.reyboz.bustorino.R; +import it.reyboz.bustorino.middleware.AppLocationManager; import it.reyboz.bustorino.backend.Route; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.backend.utils; import it.reyboz.bustorino.middleware.AppDataProvider; import it.reyboz.bustorino.middleware.NextGenDB.Contract.*; import it.reyboz.bustorino.adapters.SquareStopAdapter; +import it.reyboz.bustorino.util.LocationCriteria; import it.reyboz.bustorino.util.StopSorterByDistance; import java.util.*; public class NearbyStopsFragment extends Fragment implements LoaderManager.LoaderCallbacks { private FragmentListener mListener; - private LocationManager locManager; - private FragmentLocationListener locationListener; + private FragmentLocationListener fragmentLocationListener; private final String[] PROJECTION = {StopsTable.COL_ID,StopsTable.COL_LAT,StopsTable.COL_LONG, StopsTable.COL_NAME,StopsTable.COL_TYPE,StopsTable.COL_LINES_STOPPING}; private final static String DEBUG_TAG = "NearbyStopsFragment"; //data Bundle private final String BUNDLE_LOCATION = "location"; private final int LOADER_ID = 0; private RecyclerView gridRecyclerView; private SquareStopAdapter dataAdapter; private AutoFitGridLayoutManager gridLayoutManager; boolean canStartDBQuery = true; private Location lastReceivedLocation = null; private ProgressBar loadingProgressBar; private int distance; private SharedPreferences globalSharedPref; private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener; private TextView messageTextView; private CommonScrollListener scrollListener; private boolean firstLoc = true; public static final int COLUMN_WIDTH_DP = 250; + private Integer MAX_DISTANCE = -3; private int MIN_NUM_STOPS = -1; + private AppLocationManager locManager; public NearbyStopsFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment NearbyStopsFragment. */ public static NearbyStopsFragment newInstance() { NearbyStopsFragment fragment = new NearbyStopsFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { /* mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); */ } - locManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE); - locationListener = new FragmentLocationListener(this); + locManager = AppLocationManager.getInstance(getContext()); + fragmentLocationListener = new FragmentLocationListener(this); globalSharedPref = getContext().getSharedPreferences(getString(R.string.mainSharedPreferences),Context.MODE_PRIVATE); globalSharedPref.registerOnSharedPreferenceChangeListener(preferenceChangeListener); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View root = inflater.inflate(R.layout.fragment_nearby_stops, container, false); gridRecyclerView = (RecyclerView) root.findViewById(R.id.stopGridRecyclerView); gridLayoutManager = new AutoFitGridLayoutManager(getContext().getApplicationContext(), utils.convertDipToPixels(getContext(),COLUMN_WIDTH_DP)); gridRecyclerView.setLayoutManager(gridLayoutManager); gridRecyclerView.setHasFixedSize(false); loadingProgressBar = (ProgressBar) root.findViewById(R.id.loadingBar); messageTextView = (TextView) root.findViewById(R.id.messageTextView); preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(DEBUG_TAG,"Key "+key+" was changed"); if(key.equals(getString(R.string.databaseUpdatingPref))){ if(!sharedPreferences.getBoolean(getString(R.string.databaseUpdatingPref),true)){ canStartDBQuery = true; Log.d(DEBUG_TAG,"The database has finished updating, can start update now"); } } } }; scrollListener = new CommonScrollListener(mListener,false); return root; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof FragmentListener) { mListener = (FragmentListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onPause() { super.onPause(); canStartDBQuery = false; - locManager.removeUpdates(locationListener); + gridRecyclerView.setAdapter(null); + locManager.removeLocationRequestFor(fragmentLocationListener); Log.d(DEBUG_TAG,"On paused called"); } @Override public void onResume() { super.onResume(); canStartDBQuery = !globalSharedPref.getBoolean(getString(R.string.databaseUpdatingPref),false); try{ - if(canStartDBQuery) locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000,5,locationListener); + if(canStartDBQuery) locManager.addLocationRequestFor(fragmentLocationListener); } catch (SecurityException ex){ //ignored //try another location provider } if(dataAdapter!=null){ gridRecyclerView.setAdapter(dataAdapter); loadingProgressBar.setVisibility(View.GONE); } Log.d(DEBUG_TAG,"OnResume called"); //Re-read preferences SharedPreferences shpr = PreferenceManager.getDefaultSharedPreferences(getContext().getApplicationContext()); //For some reason, they are all saved as strings MAX_DISTANCE = shpr.getInt(getString(R.string.pref_key_radius_recents),1000); MIN_NUM_STOPS = Integer.parseInt(shpr.getString(getString(R.string.pref_key_num_recents),"12")); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); gridRecyclerView.setVisibility(View.INVISIBLE); gridRecyclerView.addOnScrollListener(scrollListener); } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public Loader onCreateLoader(int id, Bundle args) { //BUILD URI lastReceivedLocation = args.getParcelable(BUNDLE_LOCATION); Uri.Builder builder = new Uri.Builder(); builder.scheme("content").authority(AppDataProvider.AUTHORITY) .appendPath("stops").appendPath("location") .appendPath(String.valueOf(lastReceivedLocation.getLatitude())) .appendPath(String.valueOf(lastReceivedLocation.getLongitude())) .appendPath(String.valueOf(distance)); //distance CursorLoader cl = new CursorLoader(getContext(),builder.build(),PROJECTION,null,null,null); cl.setUpdateThrottle(2000); return cl; } @Override public void onLoadFinished(Loader loader, Cursor data) { ArrayList stopList = new ArrayList<>(); data.moveToFirst(); if (0 > MAX_DISTANCE) throw new AssertionError(); if(!globalSharedPref.getBoolean(getString(R.string.databaseUpdatingPref),false) && (data.getCount()0) { //quick trial to hopefully always get the stops in the correct order Collections.sort(stopList,new StopSorterByDistance(lastReceivedLocation)); if(firstLoc) { dataAdapter = new SquareStopAdapter(stopList, mListener, lastReceivedLocation); gridRecyclerView.setAdapter(dataAdapter); firstLoc = false; }else { dataAdapter.setStops(stopList); dataAdapter.setUserPosition(lastReceivedLocation); } dataAdapter.notifyDataSetChanged(); if (gridRecyclerView.getVisibility() != View.VISIBLE) { loadingProgressBar.setVisibility(View.GONE); gridRecyclerView.setVisibility(View.VISIBLE); } messageTextView.setVisibility(View.GONE); } else { messageTextView.setVisibility(View.VISIBLE); messageTextView.setText(R.string.no_stops_nearby); loadingProgressBar.setVisibility(View.GONE); } } @Override public void onLoaderReset(Loader loader) { } /** * Local locationListener, to use for the GPS */ - class FragmentLocationListener implements LocationListener{ + class FragmentLocationListener implements AppLocationManager.LocationRequester{ LoaderManager.LoaderCallbacks callbacks; private int oldLocStatus = -2; + private LocationCriteria cr; public FragmentLocationListener(LoaderManager.LoaderCallbacks callbacks) { this.callbacks = callbacks; } @Override public void onLocationChanged(Location location) { //set adapter float accuracy = location.getAccuracy(); if(accuracy<60 && canStartDBQuery) { distance = 20; final Bundle msgBundle = new Bundle(); msgBundle.putParcelable(BUNDLE_LOCATION,location); getLoaderManager().restartLoader(LOADER_ID,msgBundle,callbacks); } Log.d("LocationListener","can start loader "+ canStartDBQuery); } @Override - public void onStatusChanged(String provider, int status, Bundle extras) { - if(oldLocStatus!=status){ - - if(status == LocationProvider.OUT_OF_SERVICE || status == LocationProvider.TEMPORARILY_UNAVAILABLE) { + public void onLocationStatusChanged(int status) { + switch(status){ + case AppLocationManager.LOCATION_GPS_AVAILABLE: + messageTextView.setVisibility(View.GONE); + break; + case AppLocationManager.LOCATION_UNAVAILABLE: messageTextView.setText(R.string.enableGpsText); messageTextView.setVisibility(View.VISIBLE); - }else if(status == LocationProvider.AVAILABLE){ - messageTextView.setVisibility(View.GONE); - } - oldLocStatus = status; + break; + default: + Log.e(DEBUG_TAG,"Location status not recognized"); } } @Override - public void onProviderEnabled(String provider) { - - } - - @Override - public void onProviderDisabled(String provider) { - + public LocationCriteria getLocationCriteria() { + if(cr==null){ + cr = new LocationCriteria(60); + } + return cr; } } /** * Simple trick to get an automatic number of columns (from https://www.journaldev.com/13792/android-gridlayoutmanager-example) * */ class AutoFitGridLayoutManager extends GridLayoutManager { private int columnWidth; private boolean columnWidthChanged = true; public AutoFitGridLayoutManager(Context context, int columnWidth) { super(context, 1); setColumnWidth(columnWidth); } public void setColumnWidth(int newColumnWidth) { if (newColumnWidth > 0 && newColumnWidth != columnWidth) { columnWidth = newColumnWidth; columnWidthChanged = true; } } @Override public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { if (columnWidthChanged && columnWidth > 0) { int totalSpace; if (getOrientation() == VERTICAL) { totalSpace = getWidth() - getPaddingRight() - getPaddingLeft(); } else { totalSpace = getHeight() - getPaddingTop() - getPaddingBottom(); } int spanCount = Math.max(1, totalSpace / columnWidth); setSpanCount(spanCount); columnWidthChanged = false; } super.onLayoutChildren(recycler, state); } } } diff --git a/src/it/reyboz/bustorino/middleware/AppLocationManager.java b/src/it/reyboz/bustorino/middleware/AppLocationManager.java new file mode 100644 index 0000000..3997ab8 --- /dev/null +++ b/src/it/reyboz/bustorino/middleware/AppLocationManager.java @@ -0,0 +1,168 @@ +/* + BusTO (middleware) + Copyright (C) 2019 Fabio Mazza + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ +package it.reyboz.bustorino.middleware; + +import android.content.Context; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.location.LocationProvider; +import android.os.Bundle; +import android.util.Log; +import android.widget.Toast; +import it.reyboz.bustorino.util.LocationCriteria; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.ListIterator; + +/** + * Singleton class used to access location. Possibly extended with other location sources. + */ +public class AppLocationManager implements LocationListener { + + public static final int LOCATION_GPS_AVAILABLE = 22; + public static final int LOCATION_UNAVAILABLE = -22; + + private Context con; + private LocationManager locMan; + public static final String DEBUG_TAG = "BUSTO LocAdapter"; + private final String BUNDLE_LOCATION = "location"; + private static AppLocationManager instance; + private int oldGPSLocStatus = LOCATION_UNAVAILABLE; + + private ArrayList> requestersRef = new ArrayList<>(); + + + private AppLocationManager(Context con) { + this.con = con; + locMan = (LocationManager) con.getSystemService(Context.LOCATION_SERVICE); + } + + public static AppLocationManager getInstance(Context con) { + if(instance==null) instance = new AppLocationManager(con.getApplicationContext()); + return instance; + } + + + private void startRequestingPosition(){ + try { + locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5, this); + } catch (SecurityException exc){ + exc.printStackTrace(); + Toast.makeText(con,"Cannot access GPS location",Toast.LENGTH_SHORT).show(); + } + } + private void cleanRequesters(){ + ListIterator> iter = requestersRef.listIterator(); + while(iter.hasNext()){ + final LocationRequester cReq = iter.next().get(); + if(cReq==null) iter.remove(); + } + } + + + public void addLocationRequestFor(LocationRequester req){ + boolean present = false; + ListIterator> iter = requestersRef.listIterator(); + while(iter.hasNext()){ + final LocationRequester cReq = iter.next().get(); + if(cReq==null) iter.remove(); + else if(cReq.equals(req)){ + present = true; + } + } + if(!present) { + WeakReference newref = new WeakReference<>(req); + requestersRef.add(newref); + } + if(requestersRef.size()>0){ + startRequestingPosition(); + } + + } + public void removeLocationRequestFor(LocationRequester req){ + ListIterator> iter = requestersRef.listIterator(); + while(iter.hasNext()){ + final LocationRequester cReq = iter.next().get(); + if(cReq==null || cReq.equals(req)) iter.remove(); + } + } + private void sendLocationStatusToAll(int status){ + ListIterator> iter = requestersRef.listIterator(); + while(iter.hasNext()){ + final LocationRequester cReq = iter.next().get(); + if(cReq==null) iter.remove(); + else cReq.onLocationStatusChanged(status); + } + } + + @Override + public void onLocationChanged(Location location) { + Log.d("GPSLocationListener","found location:\nlat: "+location.getLatitude()+" lon: "+location.getLongitude()+"\naccuracy: "+location.getAccuracy()); + ListIterator> iter = requestersRef.listIterator(); + while(iter.hasNext()){ + final LocationRequester cReq = iter.next().get(); + if(cReq==null) iter.remove(); + else{ + final LocationCriteria cr = cReq.getLocationCriteria(); + if(location.getAccuracy(). + */ +package it.reyboz.bustorino.util; + +/** + * Own Location Criteria, because it's fun + */ +public class LocationCriteria { + private float minAccuracy; + public LocationCriteria(float minAccuracy){ + this.minAccuracy = minAccuracy; + } + + public float getMinAccuracy() { + return minAccuracy; + } + + public void setMinAccuracy(float minAccuracy) { + this.minAccuracy = minAccuracy; + } +}