I have this alertDialog, but when I click on the back button nothing happens:
public class LocationQueries {
Activity context;
public LocationQueries(Activity context){
this.context = context;
}
protected void promptUserToActivateGps() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage(
"GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
promptUserToActivateGps();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
How can I introduce a onBackButtonPressed method ?
Update: I updated the code. When I use it in an activity I do this :
private LocationQueries locationQueries = new LocationQueries(this);
locationQueries.promptUserToActivateGps();
Update: This is one way I can think of to achieve what you're trying to do. Basically, pass the
AlertDialog
back to theActivity
in theActivity
'sonBackPressed
-method and do the same thing as my previous answer. Here's the code:Final edit: Turns out there's an easier way to do this, as described in
alexc
's answer here, by using theAlertDialog
'ssetOnCancelListener
, which is invoked when pressing the back button while the dialog is open, as long as theAlertDialog.Builder.setCancelable()
is set totrue
.