0

I am writing an automatic downloader app and I need to clear cache of the app I am downloading from, every night. Is there a way to do this?

I searched the internet but the closest thing I found was Android: Clear Cache of All Apps? but it doesn't solve my problem because I only need to clear the data of one app.

Chaosfire
  • 4,818
  • 4
  • 8
  • 23
Mr17
  • 1
  • 3
  • If its for specific application and you know the details of it like app name or package name, add a If condition for that. – Meenal Aug 07 '23 at 21:09
  • I have the packege name, can you help me how to write codes for it ? – Mr17 Aug 09 '23 at 20:09

1 Answers1

0
public static void clearApplicationData(Context context) {
    File cache = context.getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String list : children) {
            Log.d("delete cache ", list);
            if(list.equals("shared_prefs")) continue;
            deleteDir(new File(appDir, list));
        }
    }
}

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

There's a chord like this.

First of all, you should pay attention to the log and conditional statements of the clearApplicationData function.

If you look at the log

delete cache: cache 
delete cache: shared_prefs 
delete cache: app_webview 
delete cache: code_cache 
delete cache: files 
delete cache: no_backup 
delete cache: databases 
delete cache: app_textures

Then if you have to remove the parts that you shouldn't delete

if(list.equals("shared_prefs")) continue;

You can write it like this in the conditional statement.

I wrote the conditions like this because I wanted to leave a shared preference value and delete it.

If there are more than two, not one, please write down elseif at the bottom, and the part will be skipped from the repetition to the continuation, it cannot be deleted.

When you use it, write it down like this.

clearApplicationData(getApplicationContext());
Sarah
  • 175
  • 4