如何在Android Studio中以编程方式清除应用程序的数据(共享首选项除外)

时间:2018-08-11 09:33:42

标签: android shared

我想清除我的应用程序数据,但我不想删除共享首选项

我该怎么做? 谢谢你的帮助

我使用以下代码清除所有数据:

 public void clearApplicationData() {
    File cacheDirectory = getCacheDir();
    File applicationDirectory = new File(cacheDirectory.getParent());

    File sharedPreferenceFile = new File("/data/data/"+ getPackageName()+ "/shared_prefs/");
    File[] listFiles = sharedPreferenceFile.listFiles();
    String[] fileNames1 = sharedPreferenceFile.list();


    if (applicationDirectory.exists()) {
        int i=0;
        String[] fileNames = applicationDirectory.list();
        for (String fileName : fileNames) {

            if (!fileName.equals("lib")) ) {
                deleteFile(new File(applicationDirectory, fileName));
            }

        }
    }
}

public static boolean deleteFile(File file) {
    boolean deletedAll = true;
    if (file != null) {
        if (file.isDirectory()) {
            String[] children = file.list();
            for (int i = 0; i < children.length; i++) {
                deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
            }
        } else {
            deletedAll = file.delete();
        }
    }

    return deletedAll;
}

0 个答案:

没有答案