这几天一直再做清理软件缓存这块,查了很多资料,发现这方面软件是有,但是资料很少,总结一下,高手就请飘过,希望对其他人有帮助。
这里说的清除是在软件中清理其它程序的缓存,有两种。均用到反射这方面的知识,没办法,Android系统API把这些方法隐藏了。反射就不说了,不懂得可以自己百度,谷歌!一种带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(){
@Override
public void onRemoveCompleted(String packageName,
boolean succeeded) throws RemoteException {
// TODO Auto-generated method stub
}
});
<uses-permission android:name="android.permission.DELETE_CACHE_FILES" />
另外一种是不用权限;一键清理:
private static long getEnvironmentSize()
{
File localFile = Environment.getDataDirectory();
long l1;
if (localFile == null)
l1 = 0L;
while (true)
{
String str = localFile.getPath();
StatFs localStatFs = new StatFs(str);
long l2 = localStatFs.getBlockSize();
l1 = localStatFs.getBlockCount() * l2;
return l1;
}
}
PackageManager pm = activity.getPackageManager();
Class[] arrayOfClass = new Class[2];
Class localClass2 = Long.TYPE;
arrayOfClass[0] = localClass2;
arrayOfClass[1] = IPackageDataObserver.class;
Method localMethod = pm.getClass().getMethod("freeStorageAndNotify", arrayOfClass);
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 {
// TODO Auto-generated method stub
}});
权限:<uses-permission android:name="android.permission.CLEAR_APP_CACHE" />
这也是一点点见解,还不是很成熟,希望懂的多的大牛们指出不足或者错误之处,大家共同学习一下。
可能会遇到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包下就行了。呵呵,就这么多了,各位发财...
PS:刚说不会修改,就让让我误打误撞给改过来了,汗...附件代码我已经修改好了...有问题欢迎提出!
-
用的是utf-8编码
![](http://www.eoeandroid.com/static/image/filetype/rar.gif)