【问题标题】:Clearing Cache in android App Programmatically以编程方式清除android App中的缓存
【发布时间】:2015-04-14 02:28:03
【问题描述】:

我需要有关我的 android 应用程序中缓存内存的帮助。我正在设备中运行服务器(android)。我想以编程方式清除该应用程序的缓存。我在那台服务器上有数据库。基于该数据库,我的客户操作正在进行中。所以我不希望它(数据库)生效。我只想清除缓存而不是清除数据。请帮我解决这个问题。

【问题讨论】:

  • 如果您使用的是 Kotlin,请在底部查看我的答案以获取 oneliner

标签: android performance caching


【解决方案1】:

清除缓存的代码:

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
        }
    } catch (Exception e) {}
}

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();
    }  else if (dir!= null && dir.isFile()) {
        return dir.delete();
    }
    return false;
}
【解决方案2】:
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) {
         e.printStackTrace();
      }
   }

   public static void trimCache(Context context) {
      try {
         File dir = context.getCacheDir();
         deleteDir(dir);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   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();
      }
      else {
         return false;
      }
   }

【讨论】:

    【解决方案3】:

    在 Kotlin 上你可以调用

    File(context.cacheDir.path).deleteRecursively()
    

    【讨论】:

    • 这一行代码在 Kotlin 中完美运行。
    • 当我使用此代码时,我看到“未解析的引用:上下文”
    • @manjesh23 您需要从某个地方获取上下文(如果您在活动之外),您需要将其传递给方法。例如,您也可以尝试“this”而不是 context 或“this@YourActivity”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    相关资源
    最近更新 更多