Wednesday 2 April 2014

Clear Application cache in android

There are two ways you can remove your application cache which piles up during the active state of application and free your device memory from running low on space.

1)One way you can delete cache on app exit using the following code.

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


2)Another way to manage cache is to listen for the ACTION_DEVICE_STORAGE_LOW broadcast through a &ltreceiver>.


No comments:

Post a Comment