我正在尝试计算所有缓存大小。我的代码如下..
totalSize=0;
PackageManager packageManager = context.getPackageManager();
/* List<PackageInfo> packs = packageManager
.getInstalledPackages(PackageManager.GET_ACTIVITIES);*/
// PackageManager.GET_META_DATA
List<PackageInfo> packs = packageManager
.getInstalledPackages(PackageManager.GET_META_DATA);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
Method getPackageSizeInfo;
try {
getPackageSizeInfo = packageManager.getClass().getMethod(
"getPackageSizeInfo", String.class,
IPackageStatsObserver.class);
getPackageSizeInfo.invoke(packageManager, p.packageName,
new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(
PackageStats pStats, boolean succeeded)
throws RemoteException {
totalSize = totalSize + pStats.cacheSize;
Log.d("size", totalSize+"");
Toast.makeText(context, "size"+totalSize, Toast.LENGTH_SHORT).show();
}
}
);
} catch (Exception e) {
try {
getPackageSizeInfo = packageManager.getClass().getMethod(
"getPackageSizeInfo", String.class,
IPackageStatsObserver.class);
getPackageSizeInfo.invoke(packageManager, p.packageName,
new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(
PackageStats pStats, boolean succeeded)
throws RemoteException {
totalSize = totalSize + pStats.cacheSize;
Log.d("size", totalSize+"");
Toast.makeText(context, "size"+totalSize, Toast.LENGTH_SHORT).show();
}
}
);
} catch (Exception ee) {
Log.d("eeeeeeeeeee", "error");
ee.printStackTrace();
}
}
}
Log.d("return size", totalSize+"");
Toast.makeText(context, "return size"+totalSize, Toast.LENGTH_SHORT).show();
return totalSize;
这里我得到每个包的缓存大小。问题是先返回totalSize的值,然后调用函数onGetStatsCompleted()。所以我总是得到 0 的 totalSize 值。
它也给出了例外: -
JavaBinder(525): *未捕获的远程异常!(跨进程尚不支持异常。) JavaBinder(525): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
谁能帮我?