Android一键清除所有应用的缓存


最近有一个需求,需要在最近任务页面的一键清除任务按钮中添加一键清除页面缓存的功能,网上找了一圈,看不到什么便捷的版本,基本上是遍历xxx/cache然后删除,其实是没有这个必要的。

模仿:想一想,哪里有相似功能?原生系统设置的应用信息里。

代码位置:packages\apps\Settings\src\com\android\settings\applications

类名:com.android.settings.applications. AppStorageSettings

看到这个代码时,才发现,原来如此简单。。

那么这就比较好搞定了。简陋写法:

import android.content.pm.IPackageDataObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import java.util.List;
import android.os.SystemProperties;

private ClearCacheObserver mClearCacheObserver;

void clearAllAplicationCache(){
new Thread(new Runnable() {
@Override
public void run() {
PackageManager packageManager = getPackageManager();
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
// Lazy initialization of observer
if (mClearCacheObserver==null) {
mClearCacheObserver = new ClearCacheObserver();
}
packageManager.deleteApplicationCacheFiles(packName, mClearCacheObserver);
}
}
}
}).start();
}

class ClearCacheObserver extends IPackageDataObserver.Stub {
@Override
public void onRemoveCompleted(final String packageName, final boolean succeeded) {
Log.d(TAG, packageName + " onRemoveCacheCompleted: " + succeeded);
}
}

另外附上,清除默认打开方式的代码:

PackageManager packageManager = getPackageManager();
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageManager.clearPackagePreferredActivities(packName);
try {
IBinder b = ServiceManager.getService(Context.USB_SERVICE);
IUsbManager mUsbManager = IUsbManager.Stub.asInterface(b);
mUsbManager.clearDefaults(packName, UserHandle.myUserId());
} catch (RemoteException e) {
e.printStackTrace();
}
}
}

至于, 怎么在最近任务界面加一键清除按钮,这里就不说了,附上一篇文章:

https://www.cnblogs.com/vendor/p/6375077.html

声明:TIL|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA[ZH]协议进行授权

转载:转载请注明原文链接 - Android一键清除所有应用的缓存


Life is very interesting. In the end, some of your greatest pains become your greatest strengths.