Подтвердить что ты не робот

Очистить кэш в приложении Android программно

Какой правильный способ очистить кэш в Android-приложении программно. Я уже использую следующий код, но его работа не выглядит для меня

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

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

Image from my android phone

4b9b3361

Ответ 1

Если вы ищете кеш для удаления своего собственного приложения, просто удалите кеш-каталог и все сделайте!

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;
    }
}

Ответ 2

Котлин имеет однострочник

context.cacheDir.deleteRecursively()

Ответ 3

Ответ от dhams правильный (после нескольких раз редактировался), но, как показывает множество изменений кода, сложно написать правильный и надежный код для удаления каталога (с помощью sub-dirs) самостоятельно. Поэтому я настоятельно рекомендую использовать Apache Commons IO или какой-либо другой API, который сделает это за вас:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS: Также удалите каталог, возвращаемый context.getExternalCacheDir(), если вы его используете.

Чтобы иметь возможность использовать Apache Commons IO, добавьте это в свой файл build.gradle в части dependencies:

compile 'commons-io:commons-io:2.4'

Ответ 4

Я думаю, вы должны разместить clearApplicationData() перед super.OnDestroy().

Ваше приложение не может обрабатывать какие-либо методы, когда он был закрыт.

Ответ 5

Я не уверен, но я тоже сеял этот код. эта треска будет работать быстрее и, на мой взгляд, просто. просто загрузите каталог кеша приложений и удалите все файлы в каталоге

public boolean clearCache() {
    try {

        // create an array object of File type for referencing of cache files   
        File[] files = getBaseContext().getCacheDir().listFiles();

        // use a for etch loop to delete files one by one
        for (File file : files) {

             /* you can use just [ file.delete() ] function of class File
              * or use if for being sure if file deleted
              * here if file dose not delete returns false and condition will
              * will be true and it ends operation of function by return 
              * false then we will find that all files are not delete
              */
             if (!file.delete()) {
                 return false;         // not success
             }
        }

        // if for loop completes and process not ended it returns true   
        return true;      // success of deleting files

    } catch (Exception e) {}

    // try stops deleting cache files
    return false;       // not success 
}

Он получает все файлы кеша в массиве файлов getBaseContext(). GetCacheDir(). ListFiles(), а затем удаляет один за другим в цикле методом file.delet()

Ответ 6

Попробуй это

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        int i = 0;
        while (i < children.length) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
            i++;
        }
    }

    assert dir != null;
    return dir.delete();
}

Ответ 7

Чистый Котлин (без силы опционально разворачивается)

Следуя предложениям Чистого Котлина,

object CacheHandler {

    fun deleteCache(context: Context): Boolean {
        try {
            return deleteFile(context.cacheDir)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    fun deleteFile(file: File?): Boolean {

        file?.let {
            when {
                it.isDirectory -> {
                    val children = it.list()
                    for (i in children.indices) {
                        val success = deleteFile(File(file, children[i]))
                        if (!success) {
                            return false
                        }
                    }
                    return it.delete()
                }
                it.isFile -> {
                    return it.delete()
                }
                else -> return false
            }
        }
        return false
    }
}

Вызывая пример,

mContext?.let{ CacheHandler.deleteCache(it)} // mContext is activity context

Ответ 8

Поместите этот код в метод onStop MainActivity

@Override
protected void onStop() {
    super.onStop();
    AppUtils.deleteCache(getApplicationContext());
}

....

public class AppUtils {

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        deleteDir(dir);
    } catch (Exception e) {}
}

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;
    }
}

}