Android:如何同时清除所有应用程序的缓存

时间:2012-11-29 09:34:28

标签: android android-intent

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

2 个答案:

答案 0 :(得分:-1)

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

答案 1 :(得分:-3)

不要将ClearApplicationData放在ClearApplicationDataAll之类的内容中,也不要将其放在所有应用程序的目标位置。

相关问题