Android 清理后台进程
Android 中ActivityManager提供两个方法结束后台进程:
- killBackgroundProcesses
killBackgroundProcesses 需要申请权限 android.permission.KILL_BACKGROUND_PROCESSES ,杀死的进程后根据需要进行重启,不过杀的过程中还是会释放内存.
/**
* Have the system immediately kill all background processes associated
* with the given package. This is the same as the kernel killing those
* processes to reclaim memory; the system will take care of restarting
* these processes in the future as needed.
*
* @param packageName The name of the package whose processes are to
* be killed.
*/
@RequiresPermission(Manifest.permission.KILL_BACKGROUND_PROCESSES)
public void killBackgroundProcesses(String packageName) {
try {
getService().killBackgroundProcesses(packageName,
mContext.getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
源码解释: 让系统立即终止与给定程序包关联的所有后台进程。这与内核杀死那些进程以回收内存的过程相同。系统会在将来根据需要重新启动这些过程。
后台自动清理实现
通过自定义一个服务或者悬浮窗在后台运行,获取当前运行前台运行的包名,用一个集合recentList进行存储,当数量达到多少时执行清理任务
List<String> recentList = new ArrayList<>(10); //后台包名缓存列表
/**
* 执行桌面后台启动任务清理
*
* @author lhw
*/
private synchronized void clearRecentTask() {
Log.w(TAG, "clearRecnetTask recentList==" + recentList.toString());
final ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
long beforeMem = getAvailMemory(am);
Log.w(TAG, "-----------before memory info : " + beforeMem);
if (recentList != null && recentList.size() >= 5) {
TaskScheduler.ioHandler().post(new Runnable(