Android PackageStats gives always zero

此生再无相见时 提交于 2019-11-30 16:06:57

PackageStats stats = new PackageStats(context.getPackageName());

It will only creates the packagestats object. As from the source, the constructor will do initializing the fields,

 public PackageStats(String pkgName) {
        packageName = pkgName;
        userHandle = UserHandle.myUserId();
    }

for api<26,

You need to use IPackageStatsObserver.aidl and have to invoke getPackageSizeInfo method by reflection.

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
        }
    });

Here is the complete solution for it. It works great.

from api 26,

The getPackageSizeInfo method is deprecated.

You can use this code,

 @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) {}

But to use this code, You need USAGE ACCESS PERMISSION .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!