Android手机缓存的清理

  • 步骤

    • 1.获取手机所有app缓存
    • 2.清理缓存
    • 3.获取所有app缓存(检查第二步是否成功)
  • 代码
package com.pythoncat.clearcache;import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import java.lang.reflect.Method;
import java.util.List;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private TextView tvShowCaches, tvAppCache;private Button btnScanCache, btnClearAll;private PackageManager pm;StringBuilder sb = new StringBuilder();StringBuilder sbCache = new StringBuilder();private long cacheS;Handler mHadler = new Handler();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnScanCache = (Button) findViewById(R.id.btn_scanCache);btnClearAll = (Button) findViewById(R.id.btn_clearAll);tvShowCaches = (TextView) findViewById(R.id.tv_showAppInfo);tvAppCache = (TextView) findViewById(R.id.tv_appCache);sbCache.append("所有缓存:\n");tvAppCache.setText(sbCache.toString());btnScanCache.setOnClickListener(this);btnClearAll.setOnClickListener(this);}@Overridepublic void onClick(View v) {cacheS = 0;if (v.getId() == btnScanCache.getId()) {getCaches();
//            ==========获取每个app的缓存} else if (v.getId() == btnClearAll.getId()) {cleanAll(v);getCaches();}}class MyPackageStateObserver extends IPackageStatsObserver.Stub {@Overridepublic void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {String packageName = pStats.packageName;long cacheSize = pStats.cacheSize;long codeSize = pStats.codeSize;long dataSize = pStats.dataSize;cacheS += cacheSize;
//            sb.delete(0, sb.length());if (cacheSize > 0) {sb.append("packageName = " + packageName + "\n").append("   cacheSize: " + cacheSize + "\n").append("   dataSize: " + dataSize + "\n").append("-----------------------\n");Log.e("aaaa", sb.toString());}}}class ClearCacheObj extends IPackageDataObserver.Stub {@Overridepublic void onRemoveCompleted(String packageName, final boolean succeeded) throws RemoteException {mHadler.post(new Runnable() {@Overridepublic void run() {Toast.makeText(getApplicationContext(), "清楚状态: " + succeeded, Toast.LENGTH_SHORT).show();}});}}/*** 清理全部应用程序缓存的点击事件** @param view*/public void cleanAll(View view) {//freeStorageAndNotifyMethod[] methods = PackageManager.class.getMethods();for (Method method : methods) {if ("freeStorageAndNotify".equals(method.getName())) {try {method.invoke(pm, Long.MAX_VALUE, new ClearCacheObj());} catch (Exception e) {e.printStackTrace();}return;}}}private void getCaches(){// scanpm = getPackageManager();List<PackageInfo> packages = pm.getInstalledPackages(0);int max = packages.size();int current = 0;sb.delete(0, sb.length());sb.append("所有已安装的app信息:\n");sb.append("所有App 总和:" + max + " \n");tvShowCaches.setText(sb.toString());for (PackageInfo pinfo : packages) {String packageName = pinfo.packageName;try {Method getPackageSizeInfo = PackageManager.class.getDeclaredMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class);getPackageSizeInfo.invoke(pm, packageName, new MyPackageStateObserver());current++;} catch (Exception e) {current++;e.printStackTrace();}}//===到这里,数据准备完成mHadler.postDelayed(new Runnable() {@Overridepublic void run() {Toast.makeText(getApplicationContext(),"缓存信息获取完成",Toast.LENGTH_SHORT).show();sbCache.append(Formatter.formatFileSize(getApplicationContext(),cacheS)+"\n");tvShowCaches.setText(sb.toString());tvAppCache.setText(sbCache.toString());sbCache.delete(0,sbCache.length());}}, 1000);//ok,所有应用程序信息显示完成}
}
  • 所需权限
<!-- 清除缓存时需要此权限 --><uses-permission android:name="android.permission.CLEAR_APP_CACHE" /><uses-permission android:name="android.permission.GET_PACKAGE_SIZE"/>
  • 4.所需AIDL文件
android/content/pm/IPackageDataObserver.aidl
android/content/pm/IPackageStatsObserver.aidl
android/content/pm/PackageStats.aidl
*1.PackageStats.aidl
/* //device/java/android/android/view/WindowManager.aidl
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/package android.content.pm;parcelable PackageStats;
* 2.IPackageDataObserver
/*
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/package android.content.pm;/*** API for package data change related callbacks from the Package Manager.* Some usage scenarios include deletion of cache directory, generate* statistics related to code, data, cache usage(TODO)* {@hide}*/
oneway interface IPackageDataObserver {void onRemoveCompleted(in String packageName, boolean succeeded);
}
* 3.IPackageStatsObserver
/*
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/package android.content.pm;import android.content.pm.PackageStats;
/*** API for package data change related callbacks from the Package Manager.* Some usage scenarios include deletion of cache directory, generate* statistics related to code, data, cache usage(TODO)* {@hide}*/
oneway interface IPackageStatsObserver {void onGetStatsCompleted(in PackageStats pStats, boolean succeeded);
}
  • 5.运行环境 Android 5.0
  • 6.开发环境 Android Studio
  • 7.运行效果,OK。
  • 8.完整项目已上传csdn,下载地址

Android工具开发一(清除手机所有app缓存)相关推荐

  1. Android让APP运行在新环境上,Android Studio环境在真手机运行app项目教程

    对于Android Studio环境在真手机运行app项目的相关操作有许多网友咨询过,小编今天就分享Android Studio环境在真手机运行app项目的详细步骤,一起好好学习下吧! 要想将Andr ...

  2. Android应用开发实践-茶树害虫识别App

    一.项目介绍 1 项目背景 茶树是我国的重要经济作物,防治茶树害虫有着重大意义.然而茶树病虫害不仅种类多,而且发生情况严重,茶园多处山地或丘陵地带,现场病虫害诊断和防治困难,为茶叶的生产带来严重威胁, ...

  3. android icon命名规则,安卓手机的APP图标尺寸规范和图标命名规范

    安卓手机的APP图标尺寸规范和图标命名规范 点击查看原文 android图标包括:程序启动图标.底部菜单图标.弹出对话框顶部图标.长列表内部列表项图标.底部和底部tab标签图标. 1.安卓程序启动图标 ...

  4. Android商城开发系列(二)——App启动欢迎页面制作

    商城APP一般都会在应用启动时有一个欢迎界面,下面我们来实现一个最简单的欢迎页开发:就是打开商城App,先出现欢迎界面,停留几秒钟,自动进入应用程序的主界面. 首先先定义WelcomeActivity ...

  5. 基于Android原生开发的理财小助手APP

    一.实验题目 个人理财小助手 二.实验目的 掌握 SQLite 数据库及其使用. 熟练掌握布局及常用控件 Button.ListView.EditText.TextView 等. 三.总体设计 (含背 ...

  6. android真机流量测试,手机终端app流量测试

    一.Android终端app流量测试 流量测试的原理:在安卓手机上,应用的网络流量数据都会保存在系统的/proc/uid_stat/$UID/tcp_rcv 和/proc/uid_stat/$UID/ ...

  7. 【Android工具】更新安卓手机传感器信息获取工具Ampere Castro phyphox,轻松获取硬件数据和状态信息...

    微信关注 "DLGG创客DIY" 设为"星标",重磅干货,第一时间送达. 上次分享过一个安卓手机传感器信息获取工具--Castro(本文下边),这个软件没有充电 ...

  8. 记一次用Android studio开发一个小型对话机器人app

    前言 偶然在网上看到一个免费机器人接口,所以生此想法,接口地址:http://api.qingyunke.com/,Android开发比爬虫要繁琐得多,所以本文我将细说接口的调用方法,读者可根据思路去 ...

  9. [原创]Android Monkey 在线日志分析工具开发

    [原创]Android Monkey 在线日志分析工具开发 在移动App测试过程中,Monkey测试是我们发现潜在问题的一种非常有效手段,但是Android原生的Monkey有其天然的不足,数据不能有 ...

最新文章

  1. Linux(Windows)下如何改变网卡的LinkSpeed工作模式
  2. 第十三周项目三-形状类族中的纯虚函数
  3. USACO 3.1 Agri-Net 最短网络 (最小生成树)(普里姆算法)
  4. Eureka的服务自我保护
  5. 谁将引领新一代视频编码标准:HEVC、AVS2和AV1性能对比报告
  6. Hadoop 1.x:体系结构,主要组件以及HDFS和MapReduce的工作方式
  7. Linux复习-vi编辑器
  8. 统计计算函数练pandas
  9. Oracle P6培训系列:13分配限制条件
  10. 项目管理 之四 常用的项目管理工具(Github、Gitlab、Gitea、Gitee、Worktile、Teambition)
  11. 两个微信号绑定一个服务器ip,一个手机号能绑定几个微信账号(一个手机号注册多个微信号的方法)...
  12. 访问ftp服务器网页,访问ftp服务器是网页
  13. css hr标签 各种样式
  14. html 搜索历史记录,使用cookie实现历史搜索记录功能
  15. lua时间戳和日期转换
  16. GitHub开源:支持100多种语言的OCR文字识别
  17. 微信退款服务器系统失败怎么办,微信退款多久到账?微信退款不成功怎么办?...
  18. android通讯录换ipone,换新iPhone手机,通讯录你会转移吗?90%人居然还不会!
  19. python数据分析知识_python数据分析:商品数据化运营(上)——知识点
  20. 微信里有人每天早上发的早报新闻是从哪里获取的?

热门文章

  1. 安卓开发招聘!免费Android高级工程师学习资源,2年以上经验必看
  2. 采用高德地图 实现打车功能代码
  3. 各大国外网站后台管理模块
  4. Gym - 101986F Pizza Delivery (最短路必经路径)
  5. 40行Python代码,实现卷积特征可视化
  6. PID积分饱和 和 积分分离
  7. EDM数据之大数据是什么
  8. java网络编程 TCP程序
  9. linux下c语言按q退出_linux下C语言多线程(四)线程中止
  10. 监控摄像头如何进行互联网网页实时直播