Java – Android PackageStats is always zero

Android PackageStats is always zero… here is a solution to the problem.

Android PackageStats is always zero

I’m trying to get the size my app package occupies. Each application has a place in internal/external storage.

I

want to calculate the size of the following directory, how can I do it?
I know I can use StorageStateManager in Oreo ( API 26) on devices and above, but how can I implement this before oreo devices.

Application catalog: /Android/data/myapplicationpackage

I’m trying to use PackageStats, but it always gives me zeros. What is the actual way to use this code?

I used the code below and it gives me all the zeros.

PackageStats stats = new PackageStats(context.getPackageName());
    long codeSize  = stats.codeSize + stats.externalCodeSize;
    long dataSize  = stats.dataSize + stats.externalDataSize;
    long cacheSize = stats.cacheSize + stats.externalCacheSize;
    long appSize   = codeSize + dataSize + cacheSize;

Solution

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

It only creates the packagestats object. As from the source, the constructor initializes the field

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

For api<26,

You need to use IPackageStatsObserver.aidl and you must > by reflecting the getPackageSizeInfo method /em.

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

This is complete solution for 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.

Related Problems and Solutions