Make an alert only appear when app is opened

127 views Asked by At

Is there a way to make an alert only appear when the app is opened? I'm creating an alert in onStart() in my MainActivity and whenever I go back to that activity in the app, it shows the alert again which can be annoying to the user. Or is there a way to create a "got it" button and then turn off the alert? Here is my code:

protected void onStart() {
    super.onStart();
    new AlertDialog.Builder(this)
            .setTitle("Instructions")
            .setMessage("Hello! To begin, select a map from the list to train with. Make sure" +
                    " you are on the correct floor.")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            })
            .setIcon(R.drawable.ic_launcher)
            .show();

}
2

There are 2 answers

4
Mohamed Hatem Abdu On BEST ANSWER

This is because when another activity comes to foreground upon your MainActivity makes your activity goes to OnPause(). Then when you go back to your MainActivity. The system calls onStart() again. See The activity life cycle

-First Solution

public class TestActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        showAlertDialog();
    }
}

private void showAlertDialog() {
    // code to show alert dialog.
}

}

-Second Solution

public class TestActivity extends ActionBarActivity {

private static boolean isAlertDialogShownBefore = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!isAlertDialogShownBefore) {
        showAlertDialog();
        isAlertDialogShownBefore = true;
    }
}

private void showAlertDialog() {
    // code to show alert dialog.
}

@Override
public void onBackPressed() {
    isAlertDialogShownBefore = false;
    super.onBackPressed();
}

}

0
Rajesh Batth On

Put that code in onCreate method of your activity. Check for saveInstanceState for null, if it is then show your alertDialog