The first kind of

Use the clearApplicationUserData method in ActivityManager as follows:

ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
am.clearApplicationUserData();
Copy the code

The problem with this approach is that not only does the cache clear, but the data applied is also deleted. As shown below:

The second,

Use the PackageManager deleteApplicationCacheFiles method, the API is hidden, so you need to use reflection to call, the code is as follows:

PackageManager packageManager = context.getPackageManager();
Method method;
try {
    method = PackageManager.class.getDeclaredMethod("deleteApplicationCacheFiles", String.class, IPackageDataObserver.class);
    method.invoke(packageManager, packageName, new ClearUserDataObserver());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    e.printStackTrace();
}

static class ClearUserDataObserver extends IPackageDataObserver.Stub {
    public void onRemoveCompleted(final String packageName, final boolean succeeded) {
        Log.i(TAG, "IPackageDataObserver succeeded: "+ succeeded); }}Copy the code

This method will only clear the cache. If necessary, only the cache can be cleared in this way. The IPackageDataObserver needs to be placed in the aiDI folder of the project itself, as shown below: