Clear Application cache on exit in android

后端 未结 3 982
广开言路
广开言路 2020-11-30 04:16

What I want to do is to clear the cache memory of application on exit of application.

this task i can do manually by this steps.

< Apps --> Manage

3条回答
  •  广开言路
    2020-11-30 05:02

    Try this one -

    import java.io.File;
    
    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    
    public class HelloWorld extends Activity {
    
       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle *) {
          super.onCreate(*);
          setContentView(R.layout.main);
       }
    
       @Override
       protected void onStop(){
          super.onStop();
       }
    
       //Fires after the OnStop() state
       @Override
       protected void onDestroy() {
          super.onDestroy();
          try {
             trimCache(this);
          } 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();
       }
    
    }
    

    Refer these links -

    • how-to-clear-data-cache-of-the-application-through-code

提交回复
热议问题