Reputation: 5691
I have an application which uses GPS and in the activity that the user takes action ,when pressing the "Get location" button ,it appears an alertdialog and from there the user enables the GPS.
But, when I exit the app or when I exit that activity I want to be able to disable the app.
I read that I must override the onPause method but nothing happens when I press the back arrow or when I press the home button.
GPSTracker gps;
protected LocationManager locationManager;
boolean isGPSEnabled = true;
boolean isNetworkEnabled = true;
@Override
public void onPause() {
super.onPause();
gps = new GPSTracker(MainActivity.this);
try{
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled && isNetworkEnabled) {
gps.showSettingsAlertDisable();
}
}catch (Exception e) {
e.printStackTrace();
}
}
public void showSettingsAlertDisable(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog.setMessage("Do you want to disable GPS?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
Upvotes: 0
Views: 707
Reputation: 389
Add your code to onBackPressed() or finish()
@Override
public void finish() {
if(!isCalledFromAlertDialog) {
// Show Alert Dialog - In onClickListener() set variable
// isCalledFromAlertDialog to true and call finish()
// Don't call super.finish();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(YES,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
isCalledFromAlertDialog = true;
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
return;
}
super.finish();
}
Moving code to activity would be better option else you would need to send some message to from service to notify activity about the action.
Upvotes: 1