(原)android4.2以后获取应用程序和缓存大小的方法(源码有改变)

以前获取应用的大小是用

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

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。