Android PackageStats gives always zero

后端 未结 1 1434
傲寒
傲寒 2020-12-17 04:36

I\'m trying to get the size occupied by my application package. Every application has one location in the internal/external storage.

I want to calculate the size of

相关标签:
1条回答
  • 2020-12-17 05:07

    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 .

    0 讨论(0)
提交回复
热议问题