hhayf
hhayf

Reputation: 23

Display alert only once per application launch on android

I want to add a startup alert for my application,but it keeps showing up each time I go back to the main screen.How can I do it? Newbie here and thanks in regard.

 AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setMessage("About:");
        String alert1 = "Message here " ;
        String alert2 = "Message here "  ;
        String alert3 = "Message here " ;
        alertDialog.setMessage(alert1 +"\n"+ alert2 +"\n"+ alert3); 
        AlertDialog alert = alertDialog.create();
        alert.show();

Upvotes: 1

Views: 2319

Answers (1)

joao2fast4u
joao2fast4u

Reputation: 6892

Create a boolean variable (initially set to true) to tell you if it is the first run or not and store it in Preferences.

private boolean isFirstRun = true;
private SharedPreferences prefs;

Inside on create(), read that value from Preferences in case it exists. The default value is true.

prefs = PreferenceManager.getDefaultSharedPreferences(this);
isFirstRun = prefs.getBoolean("isFirstRun", true);

Only show your Dialog if that variable value is true. Once you have shown your Dialog, set that variable to false and save it in Preferences.

if(isFirstRun){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setMessage("About:");
        String alert1 = "Message here " ;
        String alert2 = "Message here "  ;
        String alert3 = "Message here " ;
        alertDialog.setMessage(alert1 +"\n"+ alert2 +"\n"+ alert3); 
        AlertDialog alert = alertDialog.create();
        alert.show();
}

isFirstRun = false;

prefs.edit().putBoolean("isFirstRun", isFirstRun).commit();

The next times you run your code, the variable will be always false and therefore the Dialog won't show.

Edit:

Inside onStop(), do:

if(alert!=null && alert.isShowing())
   alert.dismiss();

This will dismiss the Dialog when you exit the Activity to another one. Once you press back Button, the Dialog won't show again.

Upvotes: 2

Related Questions