Reputation: 53
Every time user enters in aplication, onResume() is calling. If user doesn't respond on alert dialog, then dialogs just accumulate. I want to check is dialog already shown.
I found great answers given here: Prevent dialog to be opened multiple times when resuming activity and here How do I show only one Dialog at a time? but always was some error while implementing that in my code
Alert dialog
private AlertDialog.Builder showGPSDialog(Context con) {
AlertDialog.Builder builder = new AlertDialog.Builder(con);
builder.setTitle("Enable GPS");
builder.setMessage("Please enable GPS");
builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(
new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder;
}
onResume()
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean isEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!isEnabled) {
showGPSDialog(MapsActivity.this).show();
}
Upvotes: 1
Views: 2429
Reputation: 4633
What you can do is put boolean isDialogBox shown in sharedPreferences and make it true. When user click positive or negative button of dialogBox. and check if isDialogBox is true in onResume
Put this code in oncreate
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
private AlertDialog.Builder showGPSDialog(Context con) {
AlertDialog.Builder builder = new AlertDialog.Builder(con);
builder.setTitle("Enable GPS");
builder.setMessage("Please enable GPS");
builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
prefs.edit().putBoolean("isShown", true).commit();
startActivity(
new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
prefs.edit().putBoolean("isShown", true).commit()
dialog.dismiss();
}
});
return builder;
}
This in onResume
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean isEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!(prefs.getBoolean("isShown", false))) {
showGPSDialog(MapsActivity.this).show();
}
Upvotes: 2
Reputation: 2148
Just dismiss the dialog on the onPause method and you will only be able to have one showing
@Override
protected void onPause(){
super.onPause();
}
Upvotes: 1