Determine if Android app is being used for the first time

前端 未结 16 1257
攒了一身酷
攒了一身酷 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:43

    for kotlin

        fun checkFirstRun() {
    
        var prefs_name = "MyPrefsFile"
        var pref_version_code_key = "version_code"
        var doesnt_exist: Int = -1;
    
        // Get current version code
        var currentVersionCode = BuildConfig.VERSION_CODE
    
        // Get saved version code
        var prefs: SharedPreferences = getSharedPreferences(prefs_name, MODE_PRIVATE)
        var savedVersionCode: Int = prefs.getInt(pref_version_code_key, doesnt_exist)
    
        // Check for first run or upgrade
        if (currentVersionCode == savedVersionCode) {
    
            // This is just a normal run
            return;
    
        } else if (savedVersionCode == doesnt_exist) {
    
            // TODO This is a new install (or the user cleared the shared preferences)
    
    
        } else if (currentVersionCode > savedVersionCode) {
    
            // TODO This is an upgrade
        }
    
        // Update the shared preferences with the current version code
        prefs.edit().putInt(pref_version_code_key, currentVersionCode).apply();
    
    }
    

提交回复
热议问题