清除缓存的代码

权限
一:删除所有缓存

/** * 得到缓存大小,并开始封装数据,发送handler * * @param pm * @param info */ protected void getCatcheSpace(final PackageManager pm, final ApplicationInfo info) { try { Class clazz = Class.forName("android.content.pm.PackageManager"); Method method = clazz.getMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class); IPackageStatsObserver.Stub iPackageStatsObserver = new IPackageStatsObserver.Stub() {@Override public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {long space = pStats.cacheSize; // 得到缓存,触发handler if (space > 0) { // 有缓存 catcheInfo catcheInfo = new catcheInfo(); catcheInfo.icon = info.loadIcon(pm); catcheInfo.name = info.loadLabel(pm).toString(); catcheInfo.packagename = info.packageName; String str = Formatter.formatFileSize( getApplicationContext(), space); catcheInfo.spaceStr = str; Message msg = Message.obtain(); msg.what = CATCHEINFO; msg.obj = catcheInfo; mHandler.sendMessage(msg); } else { // 没缓存 Message msg = Message.obtain(); msg.what = ONLYNAME; msg.obj = info.loadLabel(pm); mHandler.sendMessage(msg); } // 设置进度 pb_getCatcheMessage.setProgress(++indext); if (indext >= pb_getCatcheMessage.getMax()) { mHandler.sendEmptyMessage(FINISH); } } }; // 进行运算 method.invoke(pm, info.packageName, iPackageStatsObserver); } catch (Exception e) { e.printStackTrace(); } } private class catcheInfo { public Drawable icon; public String name; public String packagename; public String spaceStr; }

二:得到每个应用的缓存
PackageManager pm = getPackageManager(); try { // 获得类名 Class clazz = Class .forName("android.content.pm.PackageManager"); // 获得方法名 Method method = clazz.getMethod("freeStorageAndNotify", long.class, IPackageDataObserver.class); // 删除成功的回调函数 IPackageDataObserver.Stub iPackageStatsObserver = new IPackageDataObserver.Stub() {@Override public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException { mHandler.sendEmptyMessage(REMOVEALL); } }; // 执行删除方法 // 参数:包管理者,想要删除多大空间(尽可能的得到),删除成功的回调函数 method.invoke(pm, Long.MAX_VALUE, iPackageStatsObserver); } catch (Exception e) { e.printStackTrace(); }

三:打开某个应用的缓存页面
Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS"); intent.addCategory("android.intent.category.DEFAULT"); intent.setData(Uri.parse("package:" + info.packagename)); startActivity(intent);

【清除缓存的代码】

    推荐阅读