Android 一鍵清理記憶體,快取,檔案程式碼
阿新 • • 發佈:2019-01-03
一鍵清理工具類:主要清理 1.系統的記憶體 2.App的快取 3.系統的臨時檔案 .apk .log .tmp .temp .back
package com.hitv.process;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
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.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.RemoteException;
import android.util.Log;
/**
* @author DongYinPing [email protected]
* @version 1.0 一鍵清理工具類:主要清理 1.系統的記憶體 2.App的快取 3.系統的臨時檔案 .apk .log .tmp .temp;
* */
public class CleanUtils {
private Context cx;
private ActivityManager am;
private PackageManager pm;
public CleanUtils(Context context) {
super();
cx = context;
am = (ActivityManager) cx.getSystemService(Context.ACTIVITY_SERVICE);
pm = cx.getPackageManager();
}
// ################################ 清理程序 ###################################
/**
* 獲取程序白名單
* */
private List<String> getFilterPackgeName() {
List<String> filterPackgeNames = new ArrayList<String>(); // 過濾一些程序
ActivityInfo launcherInfo = new Intent(Intent.ACTION_MAIN).addCategory(
Intent.CATEGORY_HOME).resolveActivityInfo(pm, 0);
filterPackgeNames.add(launcherInfo.packageName); // Launcher
filterPackgeNames.add("com.hitv.locker"); // 定時鎖屏管理
filterPackgeNames.add(cx.getPackageName()); // 自己
filterPackgeNames.add(getCurTopPackgeName()); // 過濾正在執行的程序
return filterPackgeNames;
}
/**
* 系統剩餘的記憶體
* */
public float getSurplusMemory() {
MemoryInfo info = new ActivityManager.MemoryInfo();
am.getMemoryInfo(info);
return (float) info.availMem / 1024 / 1024;
}
/**
* 系統總記憶體
* */
public float getTotalMemory() {
String str1 = "/proc/meminfo";
String str2;
String[] arrayOfString;
long initial_memory = 0;
try {
FileReader fileReader = new FileReader(str1);
BufferedReader bufferedReader = new BufferedReader(fileReader, 8192);
str2 = bufferedReader.readLine();
arrayOfString = str2.split("\\s+");
initial_memory = Integer.valueOf(arrayOfString[1]);
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return (float) (initial_memory / 1024);
}
/**
* 系統記憶體:當前使用百分比/字串格式
* */
public String usePercentNumString() {
float surplus_size = getSurplusMemory();// 剩餘MB
float all_size = getTotalMemory();// 總共MB
// 小數不足2位,以0補足
DecimalFormat decimalFormat = new DecimalFormat("0.00");
String percentnum = decimalFormat
.format((1 - surplus_size / all_size) * 100);
return percentnum;
}
/**
* 系統記憶體:當前使用百分比/數字格式
* */
public float usePercentNum() {// 用於清理後UI更新
float surplus_size = getSurplusMemory();// 剩餘MB
float all_size = getTotalMemory();// 總共MB
return (1 - surplus_size / all_size) * 100;
}
/**
* 使用反射方法呼叫系統隱藏api:forceStopPackage 通過包名殺死程序
* */
public boolean forceStopPackageByPackageName(String packageName) {
boolean forceSucceed = false;
Class<ActivityManager> clazz = ActivityManager.class;
Method method;
try {
method = clazz.getDeclaredMethod("forceStopPackage", String.class);
method.invoke(am, packageName);
forceSucceed = true;
} catch (Exception e) {
e.printStackTrace();
}
return forceSucceed;
}
/**
* 判斷是否屬於系統app
* */
public boolean isSystemApp(ApplicationInfo info) {
if ((info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
return false;// 表示是系統程式,但使用者更新過,也算是使用者安裝的程式
} else if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
return false; // 一定是使用者安裝的程式
}
return true;
}
/**
* 獲取最頂層的app包名,若是自己,則指定為其上一個
* */
public String getCurTopPackgeName() {
String curAppTaskPackgeName = null;
String myPackageName = cx.getPackageName();
List<RunningTaskInfo> appTask = am.getRunningTasks(Integer.MAX_VALUE);
if (appTask.size() > 0) {
curAppTaskPackgeName = appTask.get(0).topActivity.getPackageName();
if (appTask.size() > 1) {
if (curAppTaskPackgeName.equals(myPackageName)
&& appTask.get(1) != null) {
curAppTaskPackgeName = appTask.get(1).topActivity
.getPackageName();
}
}
}
return curAppTaskPackgeName;
}
/**
* 遍歷所有正在執行的程序列表,將所有應用的資訊傳入AppInfo中
* */
public List<AppInfo> getRunningAppProcesses() {
List<RunningAppProcessInfo> runningAppProcessInfos = am
.getRunningAppProcesses();// 正在執行的程序
List<AppInfo> appInfos = new ArrayList<AppInfo>();
List<String> filterPackgeName = getFilterPackgeName();
for (RunningAppProcessInfo appProcessInfo : runningAppProcessInfos) {
AppInfo info = new AppInfo();
int id = appProcessInfo.pid;
info.setId(id);
String appProcessName = appProcessInfo.processName;
info.setIsFilterProcess(filterPackgeName.contains(appProcessName));// 需過濾的包名
info.setPackageName(appProcessName);// 設定程序名
try {
ApplicationInfo applicationInfo = pm.getPackageInfo(
appProcessName, 0).applicationInfo;
Drawable icon = applicationInfo.loadIcon(pm);
info.setIcon(icon);
String name = applicationInfo.loadLabel(pm).toString();
info.setName(name);
info.setIsSystemProcess(isSystemApp(applicationInfo));
android.os.Debug.MemoryInfo[] memoryInfo = am
.getProcessMemoryInfo(new int[] { id });
int memory = memoryInfo[0].getTotalPrivateDirty();
info.setMemorySize(memory);
appInfos.add(info);
info = null;
} catch (Exception e) {
// e.printStackTrace();
info.setName(appProcessName);
info.setIsSystemProcess(true);
}
}
return appInfos;
}
/**
* 過濾掉系統和白名單程序 獲取最終要殺死的程序列表
* */
public ArrayList<AppInfo> getKillRunningAppProcesses() {
ArrayList<AppInfo> killRunningAppProcesses = new ArrayList<AppInfo>();
List<AppInfo> runningAppProcessInfos = getRunningAppProcesses();// 正在執行的程序
for (int i = 0; i < runningAppProcessInfos.size(); i++) {
AppInfo info = runningAppProcessInfos.get(i);
if (!info.getIsSystemProcess() && !info.getIsFilterProcess()) {
killRunningAppProcesses.add(info);
}
}
return killRunningAppProcesses;
}
/**
* 遍歷程序列表並殺死
* */
public String killProcesses(ArrayList<AppInfo> appInfos) {
float killMemorySize = 0;
for (AppInfo appInfo : appInfos) {
if (forceStopPackageByPackageName(appInfo.getPackageName())) {
float size = appInfo.getMemorySize();
Log.d("1----- DYP -----1","killProcesses-->> packageName:" + appInfo.getPackageName()+ " | size:" + size);
killMemorySize = killMemorySize + appInfo.getMemorySize();
}
}
return numToString((float) killMemorySize / 1024);
}
// ################################ 清理檔案 ###################################
/**
* 獲取單個檔案大小
* */
public float getFileSize(File file) {
float size = 0;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
size = inputStream.available();
} catch (Exception e) {
Log.d("--- DYP --- getFileSize", "catch");
// e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
return (float) size / 1024;
}
/**
* 刪除檔案,並返回檔案大小
* */
public String deleteFile(List<File> files) {
float allFileSize = 0;
float size = 0;
for (File file : files) {
size = getFileSize(file);
Log.d("3----- DYP -----3", "deleteFile-->> filePath:" + file.getPath()+ " | size:" + size);
if(file.delete()){
allFileSize = allFileSize + getFileSize(file);
}
}
// list.clear();
return numToString((float) allFileSize / 1024);
}
/**
* 查詢指定目錄下的檔案,
* */
List<File> fileList = new ArrayList<File>();
public List<File> getallFiles(String sd, String[] clearType) {
try {//遍歷可能遇到.開頭的檔案
File file = new File(sd);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
getallFiles(files[i].getAbsolutePath(), clearType);// 遞迴查詢
} else {
for (int j = 0; j < clearType.length; j++) {
if (files[i].getAbsolutePath().endsWith((clearType[j]))) {// 以.apk這些結尾
// if (files[i].getAbsolutePath().endsWith(".apk")) {
// if (isInstallApp(files[i].getAbsolutePath())) {// 安裝過可以刪除
// fileList.add(files[i]);
// }
// } else {
// fileList.add(files[i]);
// }
fileList.add(files[i]);
}
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fileList;
}
// ################################ 清理快取 ###################################
float cacheSize = 0;
/**
* 使用反射方法呼叫系統隱藏api: getPackageSizeInfo 獲取app快取大小
* */
public float getPackageSizeInfo(final String packageName) {
cacheSize = 0;
try {
Method method = PackageManager.class.getMethod(
"getPackageSizeInfo", new Class[] { String.class,
IPackageStatsObserver.class });
method.invoke(pm, new Object[] { packageName,
new IPackageStatsObserver.Stub() {
@Override
public void onGetStatsCompleted(PackageStats pStats,
boolean succeeded) throws RemoteException {
cacheSize = pStats.cacheSize;
}
} });
} catch (Exception e) {
cacheSize = 0;
// e.printStackTrace();
}
return cacheSize;
}
boolean isCleanCacheSucceed = false;
/**
* 使用反射方法呼叫系統隱藏api: deleteApplicationCacheFiles 返回清除是否成功
* */
private boolean deleteApplicationCacheFiles(String packageName) {
isCleanCacheSucceed = false;
try {
Method method = PackageManager.class.getMethod(
"deleteApplicationCacheFiles", new Class[] { String.class,
IPackageDataObserver.class });
method.invoke(pm, packageName, new IPackageDataObserver.Stub() {
@Override
public void onRemoveCompleted(String packageName,
boolean succeeded) throws RemoteException {
if(succeeded){
Log.d("DYP", "deleteApplicationCacheFiles -->> succeeded "+succeeded);
Log.d("DYP", "deleteApplicationCacheFiles -->> packageName "+packageName);
}
isCleanCacheSucceed = succeeded;
}
});
} catch (Exception e) {
// e.printStackTrace();
Log.d("DYP", "deleteApplicationCacheFiles -->> catch ");
}
return isCleanCacheSucceed;
}
float allCacheSize = 0;
/**
* 清除所有安裝app 返回的總快取
* */
public String cleanCache(List<PackageInfo> packageInfos) {
allCacheSize = 0;
for (int i = 0; i < packageInfos.size(); i++) {
String packageName = packageInfos.get(i).packageName;
if (packageName != null) {
float size = getPackageSizeInfo(packageName);
//Log.d("2----- DYP -----2", "cleanCache--> packageName:" + packageName+ " | size:" + size);
if(deleteApplicationCacheFiles(packageName)){
allCacheSize = allCacheSize + size;
Log.d("2----- DYP -----2", "cleanCache--> packageName:" + packageName+ " | size:" + size);
}
}
}
return numToString((float) allCacheSize / 1024);
}
/**
* 判斷app是否安裝
* */
public boolean isInstallApp(String abPath) {
PackageManager pm = cx.getPackageManager();
try {
pm.getPackageInfo(abPath, PackageManager.GET_ACTIVITIES);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
/**
* 獲取所有已經安裝的應用程式 ,包括那些解除安裝了的,但沒有清除資料的應用程式
* */
public List<PackageInfo> getPackageInfos() {
List<PackageInfo> packageInfos = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
// List<ApplicationInfo> listAppcations = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
return packageInfos;
}
// ############################# 將float轉化為字串形式返回 #########################
public String numToString(float f) {
// 小數不足2位,以0補足
DecimalFormat decimalFormat = new DecimalFormat("0.00");
String s = decimalFormat.format(f);
return s;
}
// ############################# 開始清理 並返回清理資料的大小 #########################
/** 清除指定垃圾檔案 */
String[] clearType = { ".apk", ".log", ".tmp", ".temp", ".bak" };
String SDCARD_ROOT = "/mnt/sdcard";
public String startDeleteFile() {
return deleteFile(getallFiles(SDCARD_ROOT, clearType));
}
public String startCleanCache() {
return cleanCache(getPackageInfos());
}
public String startkillProcesses() {
return killProcesses(getKillRunningAppProcesses());
}
}