How to delete cache-folder of app?

前端 未结 5 579
刺人心
刺人心 2020-12-14 19:48

I read through the Android documentation of the cache (see Data Storage Documentation) but I didn\'t got how I can clean the whole folder.

So how can I dele

5条回答
  •  生来不讨喜
    2020-12-14 20:31

    Put this code in onDestroy() to clear app cache:

    void onDestroy() { super.onDestroy();
    
        try {
            trimCache(this);
           // Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    }
    
    public static void trimCache(Context context) {
        try {
           File dir = context.getCacheDir();
           if (dir != null && dir.isDirectory()) {
              deleteDir(dir);
           }
        } catch (Exception e) {
           // TODO: handle exception
        }
     }
    
     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;
              }
           }
        }
    
        // The directory is now empty so delete it
        return dir.delete();
     }
    

提交回复
热议问题