clearApplicationUserData minimizes the app

2019-06-16 09:48发布

问题:

I want to erase the data of my app programatically. I've found the method clearApplicationUserData. But when I run it, the app minimizes itself. That is, the app goes to background, like when it is pressed the home button. This is my code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    ((ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE))
                        .clearApplicationUserData();
} else {
        // TODO
}

There is some way to erase data using this method without minimizing the app?

回答1:

Method ActivityManager.clearApplicationUserData() will erase all your app's data, and kill the app process directly without any warnings. I check the documentation and the source, it seems not like a bug but designed to work like that. I have some speculations as below:

  1. This method is designed for completely reset your application. Maybe you can provide your users a completely reset option.
  2. This method is designed for testing convinience (you can reset the app without reinstalling it).

If you want to implemet your own method to manage your app's data. This answer maybe helpful.



回答2:

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));

                }
            }
        }
    }
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();
    }