Determine if Android app is being used for the first time

前端 未结 16 1351
攒了一身酷
攒了一身酷 2020-11-22 12:47

I am currently developing an android app. I need to do something when the app is launched for the first time, i.e. the code only runs on the first time the program is launch

16条回答
  •  广开言路
    2020-11-22 13:45

    I solved to determine whether the application is your first time or not , depending on whether it is an update.

    private int appGetFirstTimeRun() {
        //Check if App Start First Time
        SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
        int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
        int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
    
        //Log.d("appPreferences", "app_first_time = " + appLastBuildVersion);
    
        if (appLastBuildVersion == appCurrentBuildVersion ) {
            return 1; //ya has iniciado la appp alguna vez
    
        } else {
            appPreferences.edit().putInt("app_first_time",
                    appCurrentBuildVersion).apply();
            if (appLastBuildVersion == 0) {
                return 0; //es la primera vez
            } else {
                return 2; //es una versión nueva
            }
        }
    }
    

    Compute results:

    • 0: If this is the first time.
    • 1: It has started ever.
    • 2: It has started once, but not that version , ie it is an update.

提交回复
热议问题