How to Delete Other Applications Cache from Our Android App

How to delete other applications cache from our android app?

This API is no more supported in API 23, that is Marshmallow. Permission is deprecated in Marshmallow.

But there is another way by asking run time permission for Accessories. Try app All-in-one Toolbox from play store. This app is able to clear other apps cache even in Marshmallow. Then it should be possible for us to do so.

I am researching on this. Once I found the solution, I will update the answer. Thanks.


OLD ANSWER IS AS FOLLOWS


I used the following code and now I'm able to clear all application's cache without rooting, it's working perfectly for me,

private static final long CACHE_APP = Long.MAX_VALUE;
private CachePackageDataObserver mClearCacheObserver;

btnCache.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
clearCache();
}
});//End of btnCache Anonymous class

void clearCache()
{
if (mClearCacheObserver == null)
{
mClearCacheObserver=new CachePackageDataObserver();
}

PackageManager mPM=getPackageManager();

@SuppressWarnings("rawtypes")
final Class[] classes= { Long.TYPE, IPackageDataObserver.class };

Long localLong=Long.valueOf(CACHE_APP);

try
{
Method localMethod=
mPM.getClass().getMethod("freeStorageAndNotify", classes);

/*
* Start of inner try-catch block
*/
try
{
localMethod.invoke(mPM, localLong, mClearCacheObserver);
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* End of inner try-catch block
*/
}
catch (NoSuchMethodException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}//End of clearCache() method

private class CachePackageDataObserver extends IPackageDataObserver.Stub
{
public void onRemoveCompleted(String packageName, boolean succeeded)
{

}//End of onRemoveCompleted() method
}//End of CachePackageDataObserver instance inner class

And also create a pacakge in your src folder with the name android.content.pm inside that package create a file in the name IPackageDataObserver.aidl and paste the following code to it

package android.content.pm;

/**
* API for package data change related callbacks from the Package Manager.
* Some usage scenarios include deletion of cache directory, generate
* statistics related to code, data, cache usage(TODO)
* {@hide}
*/
oneway interface IPackageDataObserver {
void onRemoveCompleted(in String packageName, boolean succeeded);
}

and in your manifest make sure you used the following code

<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>

If you guys find any problem feel free to contact me, Thanks.

How to clear the cache of another application?

        packagePath = packageInfo.applicationInfo.dataDir
val dir = File("$packagePath/cache")

You have neither read nor write access to this location for other apps. That has been true since Android 1.0, released nearly 14 years ago at this point.

How to delete app cache for all apps in Android M?

Is there an option to delete the cache of all apps or certain apps in Android M?

A third-party app cannot delete the cache of another app in Android 6.0+. The protection level of Manifest.permission.CLEAR_APP_CACHE changed from "dangerous" to "signature|privileged" or "system|signature" in Android 6.0+. Now, only apps signed with the firmware's key can hold this permission.

Is there really no way to delete app cache on devices with Android M?

Unless the app is installed as a system app or you have root access, there is no way to delete app cache on Android 6.0+.

How does the Settings app handle it?

Android is, of course, open source. Lets look at the code. In AppStorageSettings.java lines 172 - 178 we find:

if (v == mClearCacheButton) {
// Lazy initialization of observer
if (mClearCacheObserver == null) {
mClearCacheObserver = new ClearCacheObserver();
}
mPm.deleteApplicationCacheFiles(mPackageName, mClearCacheObserver);
}

So, the Settings app is using the hidden method PackageManager#deleteApplicationCacheFiles(String, IPackageDataObserver). It can do this because it holds the system level permission "android.permission.CLEAR_APP_USER_DATA" (a permission a third-party app cannot hold).


External Cache

However, cleaning of external cache is still supported.

This is still possible on Android 6.0+. I haven't looked at the source code for the app you mentioned but I would assume all you need to do is request the WRITE_EXTERNAL_STORAGE permission, get all installed packages using PackageManager, get the app's external cache directory, and delete the directory.


Root Access

Of course, if you have root access you can delete another app's cache. Here is a quick example of using root access to delete all app cache. You can use Chainfire's libsuperuser to run commands in a root shell:

PackageManager pm = getPackageManager();
List<ApplicationInfo> installedApplications = pm.getInstalledApplications(0);
for (ApplicationInfo applicationInfo : installedApplications) {
try {
Context packageContext = createPackageContext(applicationInfo.packageName, 0);
List<File> directories = new ArrayList<>();
directories.add(packageContext.getCacheDir());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Collections.addAll(directories, packageContext.getExternalCacheDirs());
} else {
directories.add(packageContext.getExternalCacheDir());
}

StringBuilder command = new StringBuilder("rm -rf");
for (File directory : directories) {
command.append(" \"" + directory.getAbsolutePath() + "\"");
}

Shell.SU.run(command.toString());
} catch (PackageManager.NameNotFoundException wtf) {
}
}

Clear another applications cache

You can only do this if the device is rooted and your application has super user rights.

How do I delete my app cache when the app is exited?

If you are looking for delete cache of your own application then simply delete your cache directory and it's all done!

public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
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) {
return false;
}
}
return dir.delete();
} else if(dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}

Android: Clear Cache of All Apps?

Here's a way to do it that doesn't require IPackageDataObserver.aidl:

PackageManager  pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("freeStorage")) {
// Found the method I want to use
try {
long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
m.invoke(pm, desiredFreeStorage , null);
} catch (Exception e) {
// Method invocation failed. Could be a permission problem
}
break;
}
}

You will need to have this in your manifest:

<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>

This requests that Android clear enough cache files so that there is 8GB free. If you set this number high enough you should achieve what you want (that Android will delete all of the files in the cache).

The way this works is that Android keeps an LRU (Least Recently Used) list of all the files in all application's cache directories. When you call freeStorage() it checks to see if the amount of storage (in this case 8GB) is available for cache files. If not, it starts to delete files from application's cache directories by deleting the oldest files first. It continues to delete files until either there are not longer any files to delete, or it has freed up the amount of storage you requested (in this case 8GB).



Related Topics



Leave a reply



Submit