5

I want to make an Android App which will clean the cache of other apps. I have figured out how to do that for Android Version below Marshmallow.

This is what I am using for Android Honeycom and above:

    if (isExternalStorageWritable()) {
        final File externalDataDirectory = new File(Environment
                .getExternalStorageDirectory().getAbsolutePath(), "/Android/data");

        final String externalCachePath = externalDataDirectory.getAbsolutePath() +
                "/%s/cache";

        if (externalDataDirectory.isDirectory()) {
            final File[] files = externalDataDirectory.listFiles();

            for (File file : files) {
                if (!deleteDirectory(new File(String.format(externalCachePath,
                        file.getName())), true)) {
                    Log.e(TAG, "External storage suddenly becomes unavailable");

                    return false;
                }
            }
        } else {
            Log.e(TAG, "External data directory is not a directory!");
        }
    } else {
        Log.d(TAG, "External storage is unavailable");
    }

But I am having an issue to figure out how to do it for Android Version Marshmallow and above.

Other cache cleaners present in the market are able to perform this by taking accessibility permission or any other way?

5
  • I'd look to see how an open source cache cleaner does it. While making that cursory search I found a note on F-droid's homepage that: "you do not need it if you are on Android 6.0 or newer. Go to Settings -> Storage & USB-> Internal storage > Cached data. In light of that might the api features your looking for been deprecated? May 19, 2019 at 10:11
  • @TrevorReid Thanks for the comment. I know the way you have suggested is one of the ways the user can clean the cache but go to each app and cleaning might not be favourable by some users additionally some users might not be aware of this and might find it difficult to do this. Hence I was searching for a way where my app can do it for users. I am sure it is possible as other apps are doing it. Any bit of advice would help me find a proper solution. Please suggest if you have any advice or a solution. May 19, 2019 at 10:21
  • What's not working with your method? I see on adb shell (not root) that rm -rf /sdcard/Android/data/com.google.android.apps.maps/cache still works on Pie.
    – rds
    May 27, 2019 at 15:55
  • @rds Thanks for the answer. But I think you have misunderstood my question. I want to make an Android App similar to Clean Master (Cache Cleaner App). I want to clear cache in my users' device which might not be rooted. Any advice or help. May 27, 2019 at 16:16
  • I have understood, and the shell command shows that what you are doing should work. Contrary to popular believe, error messages and logs can help. Anyway, I can propose an alternative method.
    – rds
    May 27, 2019 at 16:23

2 Answers 2

1
+100

Starting from Android 6.0 (Marshmallow) any normal app is not permitted to clear the cache of other apps. You can clear the cache of other apps only if your app is a system app or is signed by the same certificate the system is signed. But there is a hack on how you can.

You can perform this by using accessibility service(which is correctly pointed by you).

AFAIK you can show the cache value and then ask the user for the accessibility permission and after the permission is granted open the settings screen-->go to storage-->click the Cache button and then press ok.

Keep in mind that this is only a hack and may produce errors based on various OEM's and Android version.

Coming to how you can achieve, this is a very good example to explore how accessibility service can be used.

ALSO, KEEP IN MIND THAT YOU NEED TO TAKE PRE APPROVAL FROM GOOGLE PLAY TO USE ACCESSIBILITY OR ELSE THE MIGHT REMOVE THE APP FROM THE PLAY STORE. DO TAKE PERMISSION BEFORE GIVING AN UPDATE OR ELSE THEY MIGHT SUSPEND OR TERMINATE YOUR APP. BE VERY CAREFUL ABOUT THIS.

2
  • Thank You very much for the answer. This is exactly what I was looking for. Will post the code being used by me so that everyone can access it. Thanks once again :). May 28, 2019 at 23:55
  • I have accepted the answer and have awarded the bounty. May 28, 2019 at 23:55
0

If the application is a system app, it can request the android.permission.DELETE_CACHE_FILES and you could use reflection to access the PackageManager.deleteApplicationCacheFiles()

  // Lazily instantiated by reflection
  @Nullable private Method deleteApplicationCacheMethod;

  public ListenableFuture<Void> deleteApplicationCache(String packageName) throws Exception {
    SettableFuture<Void> futureDelete = SettableFuture.create();
    ClearCacheObserver observer = new ClearCacheObserver(packageName, deleteObserver);
    // Invoke deleteApplicationCacheFiles() by reflection
    Method deleteApplicationCacheMethod = deleteApplicationCacheMethod(packageManager);
    deleteApplicationCacheMethod.invoke(packageManager, packageName, observer);
    return futureDelete;
  }

  /** Returns an accessible version of the {@link PackageManager#deleteApplicationCacheFiles}. */
  private static Method deleteApplicationCacheMethod() throws InvocationTargetException {
    if (deleteApplicationCacheMethod == null) {
      deleteApplicationCacheMethod = packageManager
          .getClass()
          .getDeclaredMethod(
               "deleteApplicationCacheFiles", String.class, IPackageDataObserver.class);
     deleteApplicationCacheMethod.setAccessible(true);
   }
   return deleteApplicationCacheMethod;
 }

  /** Wraps a Guava Future in a IPackageDataObserver. */
  private static class ClearCacheObserver extends IPackageDataObserver.Stub {
    final String packageName;
    final SettableFuture<Void> futureDelete;

    ClearCacheObserver(String packageName, SettableFuture<Void> futureDelete) {
      this.packageName = packageName;
      this.futureDelete = futureDelete;
    }

    @Override
    public void onRemoveCompleted(String package, boolean succeeded) {
      if (!packageName.equals(package))) {
        return;
      }
      if (succeeded) {
        futureDelete.set(null);
      } else {
        futureDelete.setException(new Exception("Failed to delete cache for " + package));
      }
    }
  }
4
  • Thanks for the answer. Your answer seems to be really interesting. Will test it and update you shortly. May 27, 2019 at 16:29
  • I tried your answer but since my app does not have the Clear Cache Permission from Android M and above the solution does not work. Meanwhile what I was able to gather is that other apps use accessibility to perform this. Can you help me understand how to open the setting page in the background and then click on the storage button and then click on the clear cache button? Please Help. May 27, 2019 at 17:48
  • If you want to clear other apps cache, I think it's reasonable to request the relevant permission.
    – rds
    May 28, 2019 at 10:48
  • 1
    But the Clear Cache Permission is only granted to system apps and no normal app can request it in any manner. So the only solution is using accessibility service which will open the setting is a background and then click on the storage button and then click on the clear cache button. All this would be without the user noticing it. Can you please help with accessibility services? May 28, 2019 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.