The question is simply easy:
Explanation:
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.
The Code
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();
}
Primary needs
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
What would be the best
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.