以编程方式在Android应用程序中清除缓存

7

我需要关于Android应用程序中缓存内存的帮助。我在设备上运行服务器(android),我想通过编程方式清除该应用程序的缓存。我在该服务器上拥有数据库,基于该数据库进行客户端操作。因此,我不希望数据库受到影响。我只想清除缓存而不是清除数据。请帮助我解决这个问题。


如果您正在使用Kotlin,请查看底部的答案,其中包含一行代码。 - Merthan Erdem
3个回答

6
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;
      }
   }

6

在 Kotlin 中,您只需调用

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

1
这一行代码在 Kotlin 中完美运行。 - YaMiN
当我使用这段代码时,我看到“未解决的引用:context”提示。 - manjesh23
1
@manjesh23,你需要从某个地方获取上下文(如果你不在一个活动中),然后将其传递给该方法。你也可以尝试使用“this”代替上下文或者例如“this@YourActivity”。 - Merthan Erdem

3
清除缓存的代码:

代码如下:

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

https://dev59.com/_WAg5IYBdhLWcg3wLITS#23908638 - luckyging3r

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接