1,android本来就有获取应用缓存的方法,只是用起来有点麻烦。但我们的应用有时需要让用户知道缓存的大小,让用户及时清理缓存。
直接上代码,demo使用android studio创建。下载地址 http://pan.baidu.com/s/1sjkONzn
2,代码就一个方法。
private void getPackageSizeInfo(final String mPackageName) { try { Method getPackageSizeInfo = getPackageManager().getClass().getMethod( "getPackageSizeInfo", String.class, IPackageStatsObserver.class); getPackageSizeInfo.invoke(getPackageManager(), mPackageName, new IPackageStatsObserver.Stub() { @Override public void onGetStatsCompleted(final PackageStats pStats, boolean succeeded) throws RemoteException { runOnUiThread(new Runnable() { @Override public void run() { textView.setText("qq file code " + Formatter.formatFileSize(getApplication(), pStats.codeSize) + "\n" + "data size " + Formatter.formatFileSize(getApplication(), pStats.codeSize) + "\n" + "cache size " + Formatter.formatFileSize(getApplication(), pStats.cacheSize) + "\n" ); Log.e("content", pStats.toString()); } }); } }); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }需要权限
<uses-permission android:name="android.permission.GET_PACKAGE_SIZE"></uses-permission>
3,下面以获取qq的为例。
getPackageSizeInfo("com.tencent.mobileqq");