在android中退出时清除应用程序缓存

Aru*_*shi 14 android caching

我想要做的是在应用程序退出时清除应用程序的缓存内存.

这个任务我可以通过这个步骤手动完成.

<应用程序 - >管理应用程序 - >"我的应用程序" - >清除缓存>>

但我想通过编程退出应用程序来完成这项任务..请帮助我们..

提前致谢..

Pra*_*mar 16

试试这个 -

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

}
Run Code Online (Sandbox Code Playgroud)

参考这些链接 -

  • 不要删除主线程上的文件!您必须在其他线程上执行这些调用以避免 ANR! (2认同)

Md *_*fur 10

要清除应用程序数据请尝试这种方式.我认为它对你有帮助.

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("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) 
{
    if (dir != null &amp;&amp; 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();
}
Run Code Online (Sandbox Code Playgroud)

  • 在您的应用程序中,将有一个用户退出的活动(通常是主活动),覆盖OnDestroy()并调用上面的清除缓存代码. (2认同)