Clearing Cache in android App Programmatically
我需要一项有关我的 Android 应用程序中缓存内存的帮助。我正在设备中运行服务器(android)。我想以编程方式清除该应用程序的缓存。我在那台服务器上有数据库。基于该数据库,我的客户端操作正在进行中。所以我不希望它(数据库)受到影响。我只想清除缓存而不是清除数据。请帮我解决这个问题。
在 Kotlin 上你可以调用
1 | File(context.cacheDir.path).deleteRecursively() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 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; } } |
清除缓存的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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; } |