Android:如何同时清除所有应用程序的缓存
我对安卓非常陌生。我想开发一个用于研究的应用程序,点击一个按钮将清除android设备中所有已安装应用程序的缓存。我知道google play上有这种类型的应用程序,但我想自己开发。我尝试了以下代码,但它清除了当前一个应用程序的缓存,并抛出空指针异常。我需要同时清除每个应用程序的缓存。请帮我解决这个问题。提前谢谢Android:如何同时清除所有应用程序的缓存,android,android-intent,Android,Android Intent,我对安卓非常陌生。我想开发一个用于研究的应用程序,点击一个按钮将清除android设备中所有已安装应用程序的缓存。我知道google play上有这种类型的应用程序,但我想自己开发。我尝试了以下代码,但它清除了当前一个应用程序的缓存,并抛出空指针异常。我需要同时清除每个应用程序的缓存。请帮我解决这个问题。提前谢谢 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent
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();
}
Intent maintent=新意图(Intent.ACTION\u MAIN,空);
mainIntent.addCategory(Intent.CATEGORY_启动器);
List mainList=getPackageManager().QueryInputActivities(mainIntent,0);
语境;
对于(ResolveInfo-rInfo:mainList)
{
字符串packageName=rInfo.activityInfo.applicationInfo.packageName;
context=createPackageContext(packageName,context.context\u IGNORE\u SECURITY);
clearApplicationData(上下文);
}
public void clearApplicationData(上下文){
if(context.getCacheDir()!=null)
{
文件缓存=context.getCacheDir();
File appDir=新文件(cache.getParent());
if(appDir.exists()){
String[]children=appDir.list();
for(字符串s:子项){
如果(!s.equals(“lib”)){
deleteDir(新文件(appDir,s));
Log.i(“标签”,“文件/数据/数据/应用程序包/”+s+“删除”);
}
}
}
}
公共静态布尔deleteDir(文件目录){
if(dir!=null&&dir.isDirectory()){
String[]children=dir.list();
for(int i=0;i
不要将ClearApplicationData放在像ClearApplicationDataAll这样的东西上,或者将它放在它将针对所有应用程序的地方。
private void clearAllCache(){
PackageManager pm=getPackageManager();
方法[]methods=pm.getClass().getDeclaredMethods();
用于(方法m:方法){
if(m.getName().equals(“freeStorage”)){
试一试{
long desiredFreeStorage=long.MAX_值;
m、 调用(pm,desiredFreeStorage,null);
}捕获(例外e){
e、 printStackTrace();
}
打破
}
}
}
这个“答案”的质量很差。你有什么建议?发布合适的代码-ClearApplicationData
只是OP的方法名。千万不要这样回答。你没有指定你的逻辑建议。更改方法名对代码没有影响。你能帮助mw解决这个问题吗?