The question is simply easy:
What I am doing is to have a BroadcastReceiver that is called everytime the state of the GPS changes (enable or disable) and notifies to the user if the GPS as been disable, inviting him to reenable it (launching the relative intent).
I enable (and eventually disable) it in the root activity of my app, this way it will be called for every child activity.
My problem comes out when the user press the HOME button (for example) or open another app and disables the GPS. The notification still appears bringing my app to the front.
BroadcastReceiver
public class GPSStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains(LocationManager.GPS_PROVIDER)) {
Intent gpsIntent = new Intent(context, GPSDialogActivity.class);
gpsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
gpsIntent.putExtra(GPSDialogActivity.GPS_DIALOG_TITLE, "Attivazione GPS");
gpsIntent.putExtra(GPSDialogActivity.GPS_DIALOG_MESSAGE, "E' necessario abilitare il GPS. Cliccare su 'Usa satelliti GPS'.");
context.startActivity(gpsIntent);
}
}
}
Enable/Disable Receiver check on onCreate and onDestroy of the root Activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
*
*
Stuff
*
*
ComponentName component=new ComponentName(this, GPSStatusReceiver.class);
getPackageManager()
.setComponentEnabledSetting(component,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
@Override
protected void onDestroy() {
*
*
Stuff
*
*
*
ComponentName component=new ComponentName(this, GPSStatusReceiver.class);
getPackageManager()
.setComponentEnabledSetting(component,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
super.onDestroy();
}
What I would need is to disable BroadcastReceiver calling when the application goes to the background and enable it when the app comes back to the front
Following the above needs:
if the user disables the GPS when the app is in background (this way he should not have any notification), when he will bring the app back to the front again I intercept it and do a manual check of the GPS state and eventually notify to the user to enable the GPS.
This is one reason why fragments are useful. If you have one Activity
managing multiple fragments, the onPause()
and onResume()
of that Activity will handle registering and unregistering that receiver nicely, without the complication of child activities.
Barring that, I'd recommend subclassing Activity into a "GpsReceiverActivity", handling the registering and unregistering of the receiver in there, and using that as the baseclass of all the other activities you want to have the broadcast received by.
Well written question, by the way.