Android: First run popup dialog

Like this you can make a difference between a new install and a update.

String StoredVersionname = "";
String VersionName;
AlertDialog LoginDialog;
AlertDialog UpdateDialog;
AlertDialog FirstRunDialog;
SharedPreferences prefs;

public static String getVersionName(Context context, Class cls) {
    try {
        ComponentName comp = new ComponentName(context, cls);
        PackageInfo pinfo = context.getPackageManager().getPackageInfo(
                comp.getPackageName(), 0);
        return "Version: " + pinfo.versionName;
    } catch (android.content.pm.PackageManager.NameNotFoundException e) {
        return null;
    }
}

public void CheckFirstRun() {
    VersionName = MyActivity.getVersionName(this, MyActivity.class);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    StoredVersionname = (prefs.getString("versionname", null));
    if (StoredVersionname == null || StoredVersionname.length() == 0){
        FirstRunDialog = new FirstRunDialog(this);
        FirstRunDialog.show();
    }else if (StoredVersionname != VersionName) {
        UpdateDialog = new UpdateDialog(this);
        UpdateDialog.show();
    }
    prefs.edit().putString("versionname", VersionName).commit();
}

Use SharedPreferences to store the isFirstRun value, and check in your launching activity against that value.

If the value is set, then no need to display the dialog. If else, display the dialog and save the isFirstRun flag in SharedPreferences.

Example:

public void checkFirstRun() {
    boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);
    if (isFirstRun){
        // Place your dialog code here to display the dialog

        getSharedPreferences("PREFERENCE", MODE_PRIVATE)
          .edit()
          .putBoolean("isFirstRun", false)
          .apply();
    }
}

While the general idea of the other answers is sound, you should keep in the shared preferences not a boolean, but a timestamp of when was the last time the first run had happened, or the last app version for which it happened.

The reason for this is you'd likely want to have the first run dialog run also whenthe app was upgraded. If you keep only a boolean, on app upgrade, the value will still be true, so there's no way for your code code to know if it should run it again or not.

Tags:

Android

Dialog