Search code examples
androidcachinggoogle-playandroid-manifestandroid-permissions

How to clear app cache programmatically on every app start without system permissions in Java?


I'm working on an Android app where I need to clear the app's cache every time the app starts. I'm currently using this code to try and delete the cache:

File dir = new File(cacheFilePath);
if (dir isDirectory()){
    File[] files = dir.listFiles();
    if (files != null){
        for (File file : files){
            deleteRecursive(file);
        }
    }
}

private static void deleteRecursive(File file) {
    if (file.isDirectory()){
        File[] files = file.listFiles();
        if (files != null){
            for (File child : files){
                deleteRecursive(child);
            }
        }
    }
    file.delete();
}

However, this code does not clear the cache properly unless I try adding these permissions to the Android Manifest:

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

But I receive an underlying warning that these permissions are only granted to system apps.

Permission is only granted to the system apps.. Inspection Info: permissions with protection level signature, privileged or signeatureOrSystem are only granted to system apps, if an app is a regular non-system app, it will never be able to use these permissions.

How can I clear my app's cache programmatically without needing system permissions?

Also, if I try to publish this app on the Play Store with these permissions, will the reviewing team reject the app because of these two permissions? Are there any alternatives or best practices for handling this?


Solution

  • You don't need any permission to delete the cache of your own application

    android.permission.CLEAR_APP_CACHE is only needed when cleaning cache of other aplications, not your own
    And as you have said, it's a system apps only permission and will therefore not be granted to your app
    android.permission.DELETE_CACHE_FILES is an old persmissions and is no longer used
    Documentation: https://developer.android.com/reference/android/Manifest.permission#DELETE_CACHE_FILES

    This code you provided will do

    Also, elaborate more on what you mean

    this code does not clear the cache properly

    are some of the directories not deleted or what is not being cleared properly? The code you provided seems to do exactly what it is meant to do