备忘:清理软件缓存功能的代码
个人测试了第二种方法,是有效果的
清理软件缓存
一种带root权限的:Class c1 = Class.forName("android.content.pm.IPackageDataObserver");Method method = pm.getClass().getMethod("deleteApplicationCacheFiles", String.class,IPackageDataObserver.class);method.invoke(pm, packageName,new IPackageDataObserver.Stub(){@Overridepublic void onRemoveCompleted(String packageName,boolean succeeded) throws RemoteException {// TODO Auto-generated method stub}});
另外一种是不用root权限;一键清理:
权限:
private static long getEnvironmentSize() {
File localFile = Environment.getDataDirectory();
long l1;
if (localFile == null)
l1 = 0L;
String str = localFile.getPath();
StatFs localStatFs = new StatFs(str);
long l2 = localStatFs.getBlockSize();
l1 = localStatFs.getBlockCount() * l2;
return l1;
}
public static void clear(Activity activity) {
try {
PackageManager pm = activity.getPackageManager();
Method localMethod = pm.getClass().getMethod("freeStorageAndNotify", Long.TYPE, IPackageDataObserver.class);
Long localLong = Long.valueOf(getEnvironmentSize() - 1L);
Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = localLong;
localMethod.invoke(pm, localLong, new IPackageDataObserver.Stub() {
public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
Log.e("onRemoveCompleted,packageName="+packageName+",succeeded="+succeeded);
}
});
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
可能会遇到IPackageDataObserver这个无法导进去,自己写一个IPackageDataObserver.aidl,内容如下:package android.content.pm;/*** API for package data change related callbacks from the Package Manager.* Some usage scenarios include deletion of cache directory, generate* statistics related to code, data, cache usage(TODO)*{@hide}*/oneway interface IPackageDataObserver {void onRemoveCompleted(in String packageName, boolean succeeded);}放在src包下就行了。