Reputation: 2959
I'm developing an app in which the GPS is needed to be turned ON in order to fetch user's current location.
I'm using this code to check the current status of GPS:
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
and then I'm implementing this further code:
if (!isGPSEnabled) {
// ask to turn on GPS
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "No location detected!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getBaseContext(), "first called", Toast.LENGTH_SHORT).show();
// same codes gets executed i.e. to check if user enabled GPS or not
}
});
snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);
snackbar.show();
} else {
// execute necessary code
}
Above code is accurately checking the status of GPS, but when I'm turning the GPS on again and clicking on 'RETRY' button of Snackbar
, the code which should have get executed when GPS is ON is not getting executed, but the code which should have get executed when GPS is OFF is getting executed.
Do, I need any sort of receiver or anything to confirm that user has turned on the GPS after asking him/her to do so?
Please let me know.
Upvotes: 1
Views: 748
Reputation: 3061
I don't see any if
statement inside the onClick method, so it will execute whatever is inside that method, no matter if the user enabled or not the GPS.
If you don't mind showing the Snackbar to the user, you could also listen for Location provider changes using a broadcast receiver.
On your Activity's onCreate method:
mLocationProviderChangedReceiver = new LocalLocationProviderChangedReceiver(this);
registerReceiver(mLocationProviderChangedReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
On your Activity's onDestroy method:
if (mLocationProviderChangedReceiver != null) {
unregisterReceiver(mLocationProviderChangedReceiver);
mLocationProviderChangedReceiver = null;
}
Create an static inner class:
private static class LocalLocationProviderChangedReceiver extends BroadcastReceiver {
private final WeakReference<MyActivity> mWeakActivity;
public LocalLocationProviderChangedReceiver(@NonNull MyActivity activity) {
mWeakActivity = new WeakReference<>(activity);
}
@Override
public void onReceive(Context context, Intent intent) {
MyActivity activity = mWeakActivity.get();
if (activity != null) {
activity.refresh();
}
}
}
A refresh method in your Activity:
public void refresh() {
final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGpsEnabled) {
// TODO: Do what you need to do with the GPS
} else {
// TODO: e.g. Show a textview displaying a warning, maybe you could start the intent to activate the Location:
// Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
// startActivity(i);
}
}
Upvotes: 1