Search code examples
androidsharedpreferencesandroid-alertdialog

Show AlertDialog once after app has launched 3 times


How can I show an AltertDialog after 3 launches once? I only know how to do something at the first start of the App(I am a beginner with Android and Sharedpreferences):

if (settings.getBoolean("my_first_time", true)) {
     Log.d("Comments", "First time");

     // Action which is done at first launch
     // save first launch
     settings.edit().putBoolean("my_first_time", false).commit();
} else {
     //not first time          
}

Thank's, Felix


Solution

  • You can do it by updating sharedPreferences by 1 and check if it is equal to 3, if it is then show alertDialog.

    Here is an rough example.

    In your onCreate method, add this:

    int appLaunchedFor = getSharedPreferences("app_info", MODE_PRIVATE).getInt("counter", 0);
    
    if (appLaunchedFor == 3) {
        // Launch AlertDialog;
    
        // Now increment by 1 so that alertDialog will not launch again.
        getSharedPreferences("app_info", MODE_PRIVATE).edit().putInt("counter", ++appLaunchedFor).commit();
    } else if (appLaunchedFor < 3) {
        getSharedPreferences("app_info", MODE_PRIVATE).edit().putInt("counter", ++appLaunchedFor).commit();
    }