//回调 获取到的包信息
class PackageSizeObserver extends android.content.pm.IPackageStatsObserver.Stub {
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
throws RemoteException {
long codeSize = pStats.codeSize;
long dataSize = pStats.dataSize;
long cacheSize = pStats.cacheSize;
appCountSize+=codeSize+dataSize+cacheSize;
Log.i("zzz", "包名:"+pStats.packageName+"--------应用大小:"+Formatter.formatFileSize(MainActivity.this, codeSize+dataSize+cacheSize));
}
}
回调方法 ↑
获取程序大小,↓
PackageManager pm = this.getPackageManager();
List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES
| PackageManager.GET_DISABLED_COMPONENTS);
PackageSizeObserver observer = new PackageSizeObserver();
//通过反射机制获得该隐藏函数
Method getPackageSizeInfo = null;
try {
getPackageSizeInfo = pm.getClass().getDeclaredMethod("getPackageSizeInfo", String.class,int.class,IPackageStatsObserver.class);
//调用该函数,并且给其分配参数 ,待调用流程完成后会回调PkgSizeObserver类的函数
for (ApplicationInfo app : apps) {
getPackageSizeInfo.invoke(pm, app.packageName, Process.myUid(),observer);
}
Log.i("zzz", "appCountSize:"+Formatter.formatFileSize(MainActivity.this, appCountSize));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
注意,应该异步操作,待for循环里面的所有执行完了 所有的回调方法执行完了在更新UI 。
权限
<uses-permission android:name="android.permission.GET_PACKAGE_SIZE" />