java - 更新应用程序后如何删除数据
问题描述
如何在更新应用程序后清理数据,以便此代码在更新后仅执行一次并且数据为 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();
}
解决方案
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()
}
}
推荐阅读
- javascript - React 中这两种方法的性能差异是什么?
- php - 使用 ACF 向多个自定义字段添加 html 标记,数组自定义字段不起作用
- php - Google MyBusiness API PHP 位置
- amazon-web-services - 自动从 S3 中删除旧备份并每月移动到 Glacier
- angular - ForkJoin 无法从多个声明的主题中分叉可观察对象
- kernel-module - 如何手动安装 linux usbserial 内核驱动程序?
- node.js - NPM:如何对包进行重复数据删除?
- javascript - Match with multiple arrays
- javascript - 为 highchart 中的两个系列之一设置 minPointLength
- oracle - 如何从 oracle 错误 ORA-12704 中查找故障列