From first sight things to get GPS coordinates looks simple(pseudocode):
private void onStart() {
res = ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
if (res != PackageManager.PERMISSION_GRANTED) {
requestPermissions();
} else {
startGps();
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (all_ok)
startGps();
}
private void startGps() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {...};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
But how to handle async events:
What if after locationManager.requestLocationUpdates
user pause and resume application,
1.1 Shall I call locationManager.requestLocationUpdates
to recieve GPS data again?
1.2 What if user disable GPS when my application is paused, after user resume my app do I get onProviderDisabled
event?
How handle runtime revoking of ACCESS_FINE_LOCATION permission if it is happened after locationManager.requestLocationUpdates
call? What happening after revoking, does android report me this via onStatusChanged
or onProviderDisabled
?
I hear that new android allow several windows on screen, what happens if one window would belong to my app, another to "system preferences", and user revoke ACCESS_FINE_LOCATION without pause/resume of my app?
1.1: Its better to stop listening to GPS when your app is paused or stopped (onPause() and onStop()). This will save the battery life. So start listener again in onResume() method.
removeUpdates(locationListener)
If you dont want to removeUpdates, then you need not call call locationManager.requestLocationUpdates again.
1.2: Whenever app comes to foreground, do isProviderEnabled(provider) check and show a dialog to user.
To answer your question:
https://developer.android.com/reference/android/location/LocationManager.html
In case the provider is disabled by the user, updates will stop, and a provider availability update will be sent. As soon as the provider is enabled again, location updates will immediately resume and a provider availability update sent. Providers can also send status updates, at any time, with extra's specific to the provider. If a callback was supplied then status and availability updates are via onProviderDisabled(String), onProviderEnabled(String) or onStatusChanged(String, int, Bundle).
java.lang.SecurityException: Provider network requires ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission
If location is turned off from settings 3rd party apps will not be notified about it. You need to use isProviderEnabled(provider) method to check the location status.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With