首页 > 解决方案 > 更新应用程序后如何删​​除数据

问题描述

如何在更新应用程序后清理数据,以便此代码在更新后仅执行一次并且数据为 0kb?谢谢

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

标签: javaandroid

解决方案


Assume you have version 1.0 installed.

Save the version code in the sharedPreferences and compare app version code with the saved one every time app starts.

If you update the app, so you have 1.1 and when you start you'll see that the saved one is 1.0 and now it's 1.1. So it means you need to clear app data using your clear function.

Something like this:

fun saveVersion() {
    val currentVersion = context.packageManager
                .getPackageInfo(context.packageName, 0)
                .run {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        longVersionCode
                    } else {
                        versionCode.toLong()
                    }
                }
    val sharedPreferences: SharedPreferences = context.getSharedPreferences("myPref", Context.MODE_PRIVATE)
    sharedPreferences.edit().putLong("versionCode", currentVersion).apply()
 }

 fun getSavedVersion(): Long {
     val sharedPreferences: SharedPreferences = context.getSharedPreferences("myPref", Context.MODE_PRIVATE)
     return sharedPreferences.getLong("versionCode", -1L)
 }

and on app's MainActivity onCreate():

if (getSavedVersion() == -1L) {
   saveVersion()
} else {
   if (currentVersion > getVersion()) {
       // Then you must clear data
       clearApplicationData()
   }
}

推荐阅读