关于killBackgroundProcesses()函数,杀不死进程的解释

最近在做内存加速性质的APP,发现用killBackgroundProcesses()函数来杀一些进程总是杀不死。

经人提醒得知,不同进程的程序可能有相同的UID:比如微信,一般而言,微信有两个进程在跑:

com.tencent.mm 和 com.tencent.mm:push

无论你单独杀死哪个进程,另外一个进程在监测到兄弟进程被杀死后,就会立即启动被杀死的进程。

所以单独杀死其中一个是无用的,解决的思路就是:将拥有同一个UID的进程全部杀死。



后来补充:

通过查看ActivityManager的源码发现,真正杀不死的原因是下面这个解释:

/**
     * 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.
     * 
     * <p>You must hold the permission
     * {@link android.Manifest.permission#KILL_BACKGROUND_PROCESSES} to be able to
     * call this method.
     * 
     * @param packageName The name of the package whose processes are to
     * be killed.
     */
    public void killBackgroundProcesses(String packageName) {
        try {
            ActivityManagerNative.getDefault().killBackgroundProcesses(packageName,
                    UserHandle.myUserId());
        } catch (RemoteException e) {
        }
    }

系统会在需要的时候再次重启被我们杀死的进程。


真正彻底杀死系统进程的方法是:


/**
     * Have the system perform a force stop of everything associated with
     * the given application package.  All processes that share its uid
     * will be killed, all services it has running stopped, all activities
     * removed, etc.  In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
     * broadcast will be sent, so that any of its registered alarms can
     * be stopped, notifications removed, etc.
     * 
     * <p>You must hold the permission
     * {@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
     * call this method.
     * 
     * @param packageName The name of the package to be stopped.
     * 
     * @hide This is not available to third party applications due to
     * it allowing them to break other applications by stopping their
     * services, removing their alarms, etc.
     */
    public void forceStopPackage(String packageName) {
        try {
            ActivityManagerNative.getDefault().forceStopPackage(packageName,
                    UserHandle.myUserId());
        } catch (RemoteException e) {
        }
    }

而该方法是@hide , 并且,注释也说明得很清楚了:第三方应用不能调用该方法。

如果你想在自己的第三方app中使用该方法,那是一件很困难的事情,你不仅得获取一个操作系统的签名,还得把自己的应用设成

android:sharedUserId="android.uid.system" 权限。

这种情况作为第三方应用无疑是不可能实现的。由于该函数的功能是如此强大:该函数会停止所有和该程序包相关的:同uid程序、相关services、相关Activity等。

这也应该可以看成是Android的一种安全机制。如果第三方应用随便可以调用该函数,那么第三方应用就可以肆意来阻止竞品的程序启动以及其他破坏性工作。

一般运用这个方法来查杀进程的基本都是操作系统本身来实现靠谱一些,比如小米的MIUI,阿里的YunOS,魅族的Flyme等。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值