Java Code Examples for android.content.pm.PackageStats

The following examples show how to use android.content.pm.PackageStats. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: android_9.0.0_r45   Source File: Installer.java    License: Apache License 2.0 6 votes vote down vote up
public void getAppSize(String uuid, String[] packageNames, int userId, int flags, int appId,
        long[] ceDataInodes, String[] codePaths, PackageStats stats)
        throws InstallerException {
    if (!checkBeforeRemote()) return;
    try {
        final long[] res = mInstalld.getAppSize(uuid, packageNames, userId, flags,
                appId, ceDataInodes, codePaths);
        stats.codeSize += res[0];
        stats.dataSize += res[1];
        stats.cacheSize += res[2];
        stats.externalCodeSize += res[3];
        stats.externalDataSize += res[4];
        stats.externalCacheSize += res[5];
    } catch (Exception e) {
        throw InstallerException.from(e);
    }
}
 
Example 2
Source Project: android_9.0.0_r45   Source File: DiskStatsLoggingService.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
    FileCollector.MeasurementResult mainCategories;
    try {
        mainCategories = FileCollector.getMeasurementResult(mContext);
    } catch (IllegalStateException e) {
        // This can occur if installd has an issue.
        Log.e(TAG, "Error while measuring storage", e);
        finishJob(true);
        return;
    }
    FileCollector.MeasurementResult downloads =
            FileCollector.getMeasurementResult(mDownloadsDirectory);

    boolean needsReschedule = true;
    List<PackageStats> stats = mCollector.getPackageStats(TIMEOUT_MILLIS);
    if (stats != null) {
        needsReschedule = false;
        logToFile(mainCategories, downloads, stats, mSystemSize);
    } else {
        Log.w(TAG, "Timed out while fetching package stats.");
    }

    finishJob(needsReschedule);
}
 
Example 3
Source Project: android_9.0.0_r45   Source File: DiskStatsFileLogger.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A given package may exist for multiple users with distinct sizes. This function filters
 * the packages that do not belong to user 0 out to ensure that we get good stats for a subset.
 * @return A mapping of package name to merged package stats.
 */
private ArrayMap<String, PackageStats> filterOnlyPrimaryUser() {
    ArrayMap<String, PackageStats> packageMap = new ArrayMap<>();
    for (PackageStats stat : mPackageStats) {
        if (stat.userHandle != UserHandle.USER_SYSTEM) {
            continue;
        }

        PackageStats existingStats = packageMap.get(stat.packageName);
        if (existingStats != null) {
            existingStats.cacheSize += stat.cacheSize;
            existingStats.codeSize += stat.codeSize;
            existingStats.dataSize += stat.dataSize;
            existingStats.externalCacheSize += stat.externalCacheSize;
            existingStats.externalCodeSize += stat.externalCodeSize;
            existingStats.externalDataSize += stat.externalDataSize;
        } else {
            packageMap.put(stat.packageName, new PackageStats(stat));
        }
    }
    return packageMap;
}
 
Example 4
Source Project: styT   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
            String packageName = pStats.packageName;
            long cacheSize = pStats.cacheSize;
            long codeSize = pStats.codeSize;
            long dataSize = pStats.dataSize;
            cacheS += cacheSize;
//            sb.delete(0, sb.length());
            if (cacheSize > 0) {
                sb.append("")
                        .append("")
                        .append("")
                        .append("")
                ;

                //Log.e("aaaa", sb.toString());
            }

        }
 
Example 5
Source Project: stynico   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
            String packageName = pStats.packageName;
            long cacheSize = pStats.cacheSize;
            long codeSize = pStats.codeSize;
            long dataSize = pStats.dataSize;
            cacheS += cacheSize;
//            sb.delete(0, sb.length());
            if (cacheSize > 0) {
                sb.append("")
                        .append("")
                        .append("")
                        .append("")
                ;

                //Log.e("aaaa", sb.toString());
            }

        }
 
Example 6
Source Project: Bailan   Source File: CleanCacheActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
        throws RemoteException {
    //获取缓存
    long cache = pStats.cacheSize;
    if(cache>0){
        try {
            CacheInfo cacheInfo = new CacheInfo();
            PackageManager pm = getPackageManager();
            //添加缓存信息到ui界面
            //获取包名
            cacheInfo.packname = pStats.packageName;
            PackageInfo packInfo = pm.getPackageInfo(cacheInfo.packname, 0);
            cacheInfo.cachesize = cache;
            cacheInfo.appname = packInfo.applicationInfo.loadLabel(pm).toString();
            cacheInfo.icon = packInfo.applicationInfo.loadIcon(pm);
            Message msg = Message.obtain();
            msg.obj = cacheInfo;
            handler.sendMessage(msg);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}
 
Example 7
Source Project: AndroidDemo   Source File: StorageActivity.java    License: MIT License 6 votes vote down vote up
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {

    sb.setLength(0);
    sb.append(pStats.packageName)
            .append("\ncode = ")
            .append(getUnit(pStats.codeSize))
            .append(" ,data = ")
            .append(getUnit(pStats.dataSize))
            .append(" ,cache = ")
            .append(getUnit(pStats.cacheSize));

    Message msg = handler.obtainMessage();
    msg.obj = sb.toString();
    msg.sendToTarget();
}
 
Example 8
Source Project: AndroidGodEye   Source File: AppSizeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取应用大小8.0以下
 */
@SuppressWarnings("JavaReflectionMemberAccess")
private static void getAppSizeLowerO(Context context, @NonNull final OnGetSizeListener listener) {
    try {
        Method method = PackageManager.class.getMethod("getPackageSizeInfo", String.class,
                IPackageStatsObserver.class);
        // 调用 getPackageSizeInfo 方法,需要两个参数:1、需要检测的应用包名;2、回调
        method.invoke(context.getPackageManager(), context.getPackageName(), new IPackageStatsObserver.Stub() {
            @Override
            public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) {
                AppSizeInfo ctAppSizeInfo = new AppSizeInfo();
                ctAppSizeInfo.cacheSize = pStats.cacheSize;
                ctAppSizeInfo.dataSize = pStats.dataSize;
                ctAppSizeInfo.codeSize = pStats.codeSize;
                listener.onGetSize(ctAppSizeInfo);
            }
        });
    } catch (Throwable e) {
        listener.onError(e);
    }
}
 
Example 9
Source Project: Bailan   Source File: CleanCacheActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
        throws RemoteException {
    //获取缓存
    long cache = pStats.cacheSize;
    if(cache>0){
        try {
            CacheInfo cacheInfo = new CacheInfo();
            PackageManager pm = getPackageManager();
            //添加缓存信息到ui界面
            //获取包名
            cacheInfo.packname = pStats.packageName;
            PackageInfo packInfo = pm.getPackageInfo(cacheInfo.packname, 0);
            cacheInfo.cachesize = cache;
            cacheInfo.appname = packInfo.applicationInfo.loadLabel(pm).toString();
            cacheInfo.icon = packInfo.applicationInfo.loadIcon(pm);
            Message msg = Message.obtain();
            msg.obj = cacheInfo;
            handler.sendMessage(msg);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}
 
Example 10
Source Project: android_9.0.0_r45   Source File: Installer.java    License: Apache License 2.0 5 votes vote down vote up
public void getUserSize(String uuid, int userId, int flags, int[] appIds, PackageStats stats)
        throws InstallerException {
    if (!checkBeforeRemote()) return;
    try {
        final long[] res = mInstalld.getUserSize(uuid, userId, flags, appIds);
        stats.codeSize += res[0];
        stats.dataSize += res[1];
        stats.cacheSize += res[2];
        stats.externalCodeSize += res[3];
        stats.externalDataSize += res[4];
        stats.externalCacheSize += res[5];
    } catch (Exception e) {
        throw InstallerException.from(e);
    }
}
 
Example 11
Source Project: android_9.0.0_r45   Source File: AppCollector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(Message msg) {
    switch (msg.what) {
        case MSG_START_LOADING_SIZES: {
            List<PackageStats> stats = new ArrayList<>();
            List<UserInfo> users = mUm.getUsers();
            for (int userCount = 0, userSize = users.size();
                    userCount < userSize; userCount++) {
                UserInfo user = users.get(userCount);
                final List<ApplicationInfo> apps = mPm.getInstalledApplicationsAsUser(
                        PackageManager.MATCH_DISABLED_COMPONENTS, user.id);

                for (int appCount = 0, size = apps.size(); appCount < size; appCount++) {
                    ApplicationInfo app = apps.get(appCount);
                    if (!Objects.equals(app.volumeUuid, mVolume.getFsUuid())) {
                        continue;
                    }

                    try {
                        StorageStats storageStats =
                                mStorageStatsManager.queryStatsForPackage(app.storageUuid,
                                        app.packageName, user.getUserHandle());
                        PackageStats packageStats = new PackageStats(app.packageName,
                                user.id);
                        packageStats.cacheSize = storageStats.getCacheBytes();
                        packageStats.codeSize = storageStats.getAppBytes();
                        packageStats.dataSize = storageStats.getDataBytes();
                        stats.add(packageStats);
                    } catch (NameNotFoundException | IOException e) {
                        Log.e(TAG, "An exception occurred while fetching app size", e);
                    }
                }
            }

            mStats.complete(stats);
        }
    }
}
 
Example 12
Source Project: android_9.0.0_r45   Source File: DiskStatsLoggingService.java    License: Apache License 2.0 5 votes vote down vote up
private void logToFile(MeasurementResult mainCategories, MeasurementResult downloads,
        List<PackageStats> stats, long systemSize) {
    DiskStatsFileLogger logger = new DiskStatsFileLogger(mainCategories, downloads, stats,
            systemSize);
    try {
        mOutputFile.createNewFile();
        logger.dumpToFile(mOutputFile);
    } catch (IOException e) {
        Log.e(TAG, "Exception while writing opportunistic disk file cache.", e);
    }
}
 
Example 13
Source Project: android_9.0.0_r45   Source File: DiskStatsFileLogger.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a DiskStatsFileLogger with calculated measurement results.
 */
public DiskStatsFileLogger(MeasurementResult result, MeasurementResult downloadsResult,
        List<PackageStats> stats, long systemSize) {
    mResult = result;
    mDownloadsSize = downloadsResult.totalAccountedSize();
    mSystemSize = systemSize;
    mPackageStats = stats;
}
 
Example 14
Source Project: android_9.0.0_r45   Source File: DiskStatsFileLogger.java    License: Apache License 2.0 5 votes vote down vote up
private void addAppsToJson(JSONObject json) throws JSONException {
    JSONArray names = new JSONArray();
    JSONArray appSizeList = new JSONArray();
    JSONArray appDataSizeList = new JSONArray();
    JSONArray cacheSizeList = new JSONArray();

    long appSizeSum = 0L;
    long appDataSizeSum = 0L;
    long cacheSizeSum = 0L;
    boolean isExternal = Environment.isExternalStorageEmulated();
    for (Map.Entry<String, PackageStats> entry : filterOnlyPrimaryUser().entrySet()) {
        PackageStats stat = entry.getValue();
        long appSize = stat.codeSize;
        long appDataSize = stat.dataSize;
        long cacheSize = stat.cacheSize;
        if (isExternal) {
            appSize += stat.externalCodeSize;
            appDataSize += stat.externalDataSize;
            cacheSize += stat.externalCacheSize;
        }
        appSizeSum += appSize;
        appDataSizeSum += appDataSize;
        cacheSizeSum += cacheSize;

        names.put(stat.packageName);
        appSizeList.put(appSize);
        appDataSizeList.put(appDataSize);
        cacheSizeList.put(cacheSize);
    }
    json.put(PACKAGE_NAMES_KEY, names);
    json.put(APP_SIZES_KEY, appSizeList);
    json.put(APP_CACHES_KEY, cacheSizeList);
    json.put(APP_DATA_KEY, appDataSizeList);
    json.put(APP_SIZE_AGG_KEY, appSizeSum);
    json.put(APP_CACHE_AGG_KEY, cacheSizeSum);
    json.put(APP_DATA_SIZE_AGG_KEY, appDataSizeSum);
}
 
Example 15
Source Project: styT   Source File: via_webviwe.java    License: Apache License 2.0 5 votes vote down vote up
@Override
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
            long cacheSize = pStats.cacheSize;
//            sb.delete(0, sb.length());
            if (cacheSize > 0) {

            }

        }
 
Example 16
Source Project: stynico   Source File: AnimatedEditText.java    License: MIT License 5 votes vote down vote up
@Override
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
            String packageName = pStats.packageName;
            long cacheSize = pStats.cacheSize;
            long codeSize = pStats.codeSize;
            long dataSize = pStats.dataSize;
//            sb.delete(0, sb.length());
            if (cacheSize > 0) {

	    }

        }
 
Example 17
Source Project: stynico   Source File: dex_smali.java    License: MIT License 5 votes vote down vote up
@Override
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
            String packageName = pStats.packageName;
            long cacheSize = pStats.cacheSize;
            long codeSize = pStats.codeSize;
            long dataSize = pStats.dataSize;
//            sb.delete(0, sb.length());
            if (cacheSize > 0) {
		
	    }

        }
 
Example 18
Source Project: FileManager   Source File: SysCacheScanTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
    mScanCount++;
    if (succeeded && pStats != null) {
        JunkInfo info = new JunkInfo();
        info.setPackageName(pStats.packageName)
                .setName(pStats.packageName)
                .setSize(pStats.cacheSize + pStats.externalCacheSize);

        if (info.getSize() > 0) {
            mSysCaches.add(info);
            mTotalSize += info.getSize();
        }
        mCallBack.onProgress(info);
    }

    if (mScanCount == mTotalCount) {
        JunkInfo junkInfo = new JunkInfo();
        junkInfo.setName(App.sContext.getString(R.string.system_cache))
                .setSize(mTotalSize)
                .setChildren(mSysCaches)
                .setVisible(true)
                .setChild(false)
                .isCheck(false);

        Collections.sort(mSysCaches);
        Collections.reverse(mSysCaches);

        ArrayList<JunkInfo> list = new ArrayList<>();
        list.add(junkInfo);
        mCallBack.onFinish(list);
    }
}
 
Example 19
Source Project: MobileGuard   Source File: AppManagerEngine.java    License: MIT License 5 votes vote down vote up
/**
 * get app size by package name
 * @param context
 * @param packageName package name
 * @param listener it will be call when success to get size
 */
public static void getAppSize(Context context, String packageName, final AppSizeInfoListener listener) {
    // check argument
    if(null == listener) {
        throw new NullPointerException("listener can't be null");
    }
    if(TextUtils.isEmpty(packageName)) {
        throw  new IllegalArgumentException("packageName can't be empty");
    }

    // get pm
    PackageManager pm = context.getPackageManager();
    Method getPackageSizeInfo = null;
    try {
        // get method getPackageSizeInfo
        getPackageSizeInfo = pm.getClass().getMethod(
                "getPackageSizeInfo",
                String.class, IPackageStatsObserver.class);
        // call method
        getPackageSizeInfo.invoke(pm, packageName,
                new IPackageStatsObserver.Stub() {
                    @Override
                    public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
                            throws RemoteException {
                        // call listener
                        listener.onGetSizeInfoCompleted(
                                new AppSizeInfo(pStats.cacheSize, pStats.dataSize, pStats.codeSize));
                    }
                });
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 20
Source Project: FlyWoo   Source File: AppUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 返回用户已安装应用列表
 */
public static List<AppEntity> getAppList(Context context) {
    PackageManager pm = context.getPackageManager();
    List<PackageInfo> packageInfos = pm.getInstalledPackages(0);
    List<AppEntity> appInfos = new ArrayList<AppEntity>();
    for (PackageInfo packageInfo : packageInfos) {

        ApplicationInfo app = packageInfo.applicationInfo;
        if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
            // 非系统应用
            File apkfile = new File(app.sourceDir);
            PackageStats stats = new PackageStats(packageInfo.packageName);
            AppEntity appInfo = new AppEntity(app.sourceDir);
            appInfo.setPackageName(packageInfo.packageName);
            appInfo.setVersionCode(packageInfo.versionCode);
            appInfo.setVersionName(packageInfo.versionName);
            appInfo.setUid(app.uid);
            appInfo.setIcon(app.loadIcon(pm));
            appInfo.setAppName(app.loadLabel(pm).toString());
            appInfo.setCacheSize(stats.cacheSize);
            appInfo.setDataSize(stats.dataSize);
            appInfos.add(appInfo);
        }

    }

    return appInfos;
}
 
Example 21
Source Project: android-cache-cleaner   Source File: CleanerService.java    License: MIT License 5 votes vote down vote up
private long addPackage(List<AppsListItem> apps, PackageStats pStats, boolean succeeded) {
    long cacheSize = 0;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        cacheSize += pStats.cacheSize;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        cacheSize += pStats.externalCacheSize;
    }

    if (!succeeded || cacheSize <= 0) {
        return 0;
    }

    try {
        PackageManager packageManager = getPackageManager();
        ApplicationInfo info = packageManager.getApplicationInfo(pStats.packageName,
                PackageManager.GET_META_DATA);

        apps.add(new AppsListItem(pStats.packageName,
                packageManager.getApplicationLabel(info).toString(),
                packageManager.getApplicationIcon(pStats.packageName),
                cacheSize));
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    return cacheSize;
}
 
Example 22
Source Project: android-cache-cleaner   Source File: CleanerService.java    License: MIT License 4 votes vote down vote up
@Override
protected List<AppsListItem> doInBackground(Void... params) {
    mCacheSize = 0;

    final List<ApplicationInfo> packages = getPackageManager().getInstalledApplications(
            PackageManager.GET_META_DATA);

    publishProgress(0, packages.size());

    final CountDownLatch countDownLatch = new CountDownLatch(packages.size());

    final List<AppsListItem> apps = new ArrayList<>();

    try {
        for (ApplicationInfo pkg : packages) {
            mGetPackageSizeInfoMethod.invoke(getPackageManager(), pkg.packageName,
                    new IPackageStatsObserver.Stub() {

                        @Override
                        public void onGetStatsCompleted(PackageStats pStats,
                                                        boolean succeeded)
                                throws RemoteException {
                            synchronized (apps) {
                                publishProgress(++mAppCount, packages.size());

                                mCacheSize += addPackage(apps, pStats, succeeded);
                            }

                            synchronized (countDownLatch) {
                                countDownLatch.countDown();
                            }
                        }
                    }
            );
        }

        countDownLatch.await();
    } catch (InvocationTargetException | InterruptedException | IllegalAccessException e) {
        e.printStackTrace();
    }

    return new ArrayList<>(apps);
}
 
Example 23
void onPackageStats(PackageStats packageStats);