我对安卓很陌生。我想开发一个应用程序进行研究,单击一个按钮将清除 android 设备中所有已安装应用程序的缓存。我知道这种类型的应用程序在 google play 上可用,但我想自己开发。我尝试以下代码,但它清除了当前一个应用程序的缓存并抛出空指针异常。我需要同时清除每个应用程序的缓存。请帮我解决这个问题。在此先感谢..
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();
}