Android: How to reset FirstRun SharedPreferences when my app is updated?

后端 未结 4 1228
盖世英雄少女心
盖世英雄少女心 2020-12-14 04:14

My app copies files over from res/raw to the sdcard on first run. I want it to update those files on every subsequent app update. How can i have it reset the firstrun prefer

4条回答
  •  猫巷女王i
    2020-12-14 04:27

    Run this in the MainActivity's OnCreate

    public void onUpdateFirstRun () {
        SharedPreferences prefs  = PreferenceManager.getDefaultSharedPreferences(this);
        PackageInfo pInfo;
    
        try {
            pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
    
            Log.d("VersionCode", pInfo.versionCode + " ");
            if (prefs.getLong(LAST_RUN_VERSION_CODE_KEY, 0) < pInfo.versionCode) {
    
                if (!isInitializedInSP(KEY)) {
    
                    editor.putString(KEY, "");
                }
    
                //Finalize and Save
                editor.putLong(LAST_RUN_VERSION_CODE_KEY, pInfo.versionCode);
                editor.apply();
    
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    

    Use method to check if you had already initialized it in previous version

    public static boolean isInitializedInSP (String key) {
        SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContex());
        Object o = mPrefs.getAll().get(key);
    
        if (o != null) {
            return true;
        }
        else  {
            return false;
        }
    
    }
    

提交回复
热议问题