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();    @Override    protected 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);    }    @Override    public 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 {        @Override        public 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 {        @Override        public void onRemoveCompleted(String packageName, final boolean succeeded) throws RemoteException {            mHadler.post(new Runnable() {                @Override                public void run() {                    Toast.makeText(getApplicationContext(), "清楚状态: " + succeeded, Toast.LENGTH_SHORT).show();                }            });        }    }    /**     * 清理全部应用程序缓存的点击事件     *     * @param view     */    public void cleanAll(View view) {        //freeStorageAndNotify        Method[] 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(){        // scan        pm = getPackageManager();        List 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() {            @Override            public 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.aidlandroid/content/pm/IPackageStatsObserver.aidlandroid/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,下载地址

更多相关文章

  1. android 获取手机的所有程序和widget的包名和启动类名
  2. Android(安卓)SQLiteStatement 编译、执行 分析
  3. Android(安卓)layer-list 中图片被拉伸问题
  4. 缓存
  5. 欢迎下载科幻世界iPhone、iPad、Android手机客户端
  6. CM13.0代码下载
  7. [转]新浪微博AppKey大集合
  8. Android音视频处理之MediaExtractor
  9. Qt5.12.1 for Android配置

随机推荐

  1. Bootstrap 学习 - 网格系统
  2. MPU6050姿态解算2-欧拉角&旋转矩阵
  3. FreeRTOS例程4-串口DMA收发不定长数据
  4. 欧拉角旋转
  5. FreeRTOS例程3-串口中断接收不定长的数据
  6. 3维旋转矩阵推导与助记-补充篇
  7. 各种类型的指针作业解析(C语言)
  8. 3维旋转矩阵推导与助记
  9. C语言字符串相关函数使用示例 strtok_r s
  10. springboot2.x引入Mybatis-plus-generato