PackageStats stats = new PackageStats(context.getPackageName());
它只会创建 packagestats 对象。从源头开始,构造函数将初始化字段,
public PackageStats(String pkgName) {
packageName = pkgName;
userHandle = UserHandle.myUserId();
}
对于 api<26,
您需要使用并且必须通过反射IPackageStatsObserver.aidl
调用getPackageSizeInfo
方法。
PackageManager pm = getPackageManager();
Method getPackageSizeInfo = pm.getClass().getMethod(
"getPackageSizeInfo", String.class, IPackageStatsObserver.class);
getPackageSizeInfo.invoke(pm, "com.yourpackage",
new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
throws RemoteException {
//here the pStats has all the details of the package
}
});
这是它的完整解决方案。它工作得很好。
从 api 26 开始,
该getPackageSizeInfo
方法已弃用。
您可以使用此代码,
@SuppressLint("WrongConstant")
final StorageStatsManager storageStatsManager = (StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE);
final StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(packagename, 0);
StorageStats storageStats = storageStatsManager.queryStatsForUid(ai.storageUuid, info.uid);
cacheSize =storageStats.getCacheBytes();
dataSize =storageStats.getDataBytes();
apkSize =storageStats.getAppBytes();
size+=info.cacheSize;
} catch (Exception e) {}
但要使用此代码,您需要USAGE ACCESS PERMISSION。