以前获取应用的大小是用
PackageManager mPackageManager= getPackageManager();
try {Method getPackageSizeInfoMethod = PackageManager.class.getDeclaredMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class); getPackageSizeInfoMethod.invoke(mPackageManager, packageInfo.packageName,new MyObserver()); } catch (Exception e) { }
class MyObserver extends IPackageStatsObserver.Stub { @Override public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException { long cacheSize = pStats.cacheSize; String packageName = pStats.packageName; String formatFileSize = Formatter.formatFileSize( getApplicationContext(), cacheSize); System.out.println(packageName + ":" + formatFileSize); } }
但在4.2后 PackageManager.getPackageSizeInfo(String packageName, IPackageStatsObserver observer)不可用,
改为PackageManager.getPackageSizeInfo(String packageName, int userHandle, IPackageStatsObserver observer),
至于增加的参数userHandle的解释是:The user whose size information should be retrieved。
这个userHandle怎么来? 通过系统类的UserHandle.myUserId()获取;
Method myUserId = UserHandle.class.getDeclaredMethod("myUserId"); int userID = (Integer) myUserId.invoke(mPackageManager,null);
获取了以后就可以使用新的getPackageSizeInfo函数了。
getPackageSizeInfoMethod.invoke(mPackageManager,packageInfo.packageName, userID, new MyObserver() );
时间: 2024-11-09 02:09:29