[英]Android: How to clear cache of all application simultaneously
我對android很新。 我想開發一個學習應用程序,點擊一個按鈕將清除Android設備中所有已安裝應用程序的緩存內存。我知道這種類型的應用程序可以在谷歌播放,但我想自己開發。 我嘗試以下代碼,但它清除當前一個應用程序的緩存內存並拋出空指針異常。 我需要同時清除每個應用程序的緩存。 請幫我解決這個問題。謝謝提前..
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> mainList = getPackageManager().queryIntentActivities(mainIntent, 0);
Context context;
for(ResolveInfo rInfo : mainList)
{
String packageName = rInfo.activityInfo.applicationInfo.packageName;
context = createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
clearApplicationData(context);
}
public void clearApplicationData(Context context) {
if(context.getCacheDir()!=null)
{
File cache = context.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 && 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();
}
private void clearAllCache() { PackageManager pm = getPackageManager(); Method[] methods = pm.getClass().getDeclaredMethods(); for (Method m : methods) { if (m.getName().equals("freeStorage")) { try { long desiredFreeStorage = Long.MAX_VALUE; m.invoke(pm, desiredFreeStorage , null); } catch (Exception e) { e.printStackTrace(); } break; } } }
而不是將ClearApplicationData放在像ClearApplicationDataAll這樣的東西上,或者將它放在目標所有應用程序的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.