Clearing android cache

2019-04-14 07:20发布

Hi I've got an app with a code size of approximately 1/2mb. The app includes a webview for showing several pages. My cache therefore ends up at 2,5mb. Not much but enough. How can I clear my cache onDestroy?

Thx!

2条回答
虎瘦雄心在
2楼-- · 2019-04-14 07:42

put this code in onDestroy() for clear app cache

@Override
    protected 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();
     }
查看更多
ゆ 、 Hurt°
3楼-- · 2019-04-14 07:42

As given in the link provided above, you can get the cache directory and then delete it along with its children to clear the cache as follows:

    File dir = context.getCacheDir(); 
    if (dir != null && dir.isDirectory()) { 
     deleteDir(dir); 
    } 


    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(); 
   }
查看更多
登录 后发表回答