Android 清理后台进程

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(
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值