我想知道有关如何在用户为我的应用程序选择卸载按钮后删除文件夹的信息。我希望通过编程方式来做到这一点...如果是这样,请告诉我可能的解决方案。预先感谢。
如果您在设备的外部存储设备上创建了任何文件夹,则当用户卸载应用程序时,您将无法调用代码。某些内容会自动删除(数据库,所有写入内部存储的内容),但不会删除外部存储上的文件夹。
编辑-正如Stephan所指出的,如果您的目标是API Level 8或更高版本,则可以将Context.getExternalFilesDir()用于外部文件,并且这些文件在卸载时将被删除。
这里是个主意。如果您担心在卸载过程中未删除的文件会在以后如this question中重新安装您的应用程序时使用户的入职过程混乱,那么您可以简单地确保在安装时删除了所有数据。重新安装您的应用程序(或为此简单地安装)。这是“如果穆罕默德不去那座山,那座山就会去穆罕默德”。显然,您必须在共享首选项中设置一个标志,因此删除外部存储目录内容的过程仅在用户与您的应用进行首次交互之前执行一次,这里是一些示例代码:
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstInteraction = sharedPreferences.getBoolean("isFirstUsage", true);
if(isFirstInteraction){
trimCache(this);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("isFirstUsage",false);
editor.apply();
}
//delete files from external files dir
public static void trimStorage(Context context) {
try {
File dir = context.getExternalFilesDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
e.printStackTrace();
}
}
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) {
Log.d("deletion","failed at "+children[i]);
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}