Android AMS 杀进程场景之汇总

基于Android 6.0源码剖析,统计AMS所有可能杀进程的场景.

一. 杀进程场景

理解杀进程的实现原理, 介绍了杀进程的过程, 接下来本文介绍系统framework层, ActivityManagerService在哪些场景会调用ProcessRecord.java中的kill()方法来杀进程.

    void kill(String reason, boolean noisy) {
        if (!killedByAm) {
            if (noisy) {
                Slog.i(TAG, "Killing " + toShortString() + " (adj " + setAdj + "): " + reason);
            }
            //调用该方法,则会输出EventLog, 最后一个参数reason代表是通过何在方法触发kill
            EventLog.writeEvent(EventLogTags.AM_KILL, userId, pid, processName, setAdj, reason);
            Process.killProcessQuiet(pid);
            Process.killProcessGroup(info.uid, pid);
            if (!persistent) {
                killed = true;
                killedByAm = true;
            }
        }
    }

reason对于分析问题很重要, 实例说明:

    am_kill : [0,26328,com.gityuan.app,0,stop com.gityuan.app]

这是Eventlog,可知最后一个参数stop com.gityuan.app, 代表的是reason = stop packageName, 那么显然这个app是由于调用forceStopPackageLocked而被杀.
先看重点说说force-stop

1.1 force-stop

对于force-stop系统这把杀进程的利器, 还会额外出现一个reason来更详细的说明触发force-stop的原因.

    Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId + " user=" + userId + ": " + reason);

以下场景都会调用force-stop, 输出reason表格如下:

方法 reason 含义
AMS.forceStopPackage from pid callingPid
AMS.finishUserStop finish user
AMS.clearApplicationUserData clear data
AMS.broadcastIntentLocked storage unmount
AMS.finishBooting query restart
AMS.finishInstrumentationLocked finished inst evenPersistent
AMS.setDebugApp set debug app evenPersistent
AMS.startInstrumentation start instrevenPersistent
PKMS.deletePackageLI uninstall pkg
PKMS.movePackageInternal move pkg
PKMS.replaceSystemPackageLI replace sys pkg
PKMS.scanPackageDirtyLI replace pkg
PKMS.scanPackageDirtyLI update lib
PKMS.setApplicationHiddenSettingAsUser hiding pkg
MountService.killMediaProvider vold reset

PKMS服务往往是调用killApplication从而间接调用forceStopPackage方法.

当然除了force-stop, 杀进程的原因(reason)有很多种形式, 如下:

1.2 异常杀进程

方法 reason 含义
appNotResponding anr ANR
appNotResponding bg anr ANR
handleAppCrashLocked crash CRASH
crashApplication crash CRASH
processStartTimedOutLocked start timeout
processContentProviderPublishTimedOutLocked timeout publishing content providers
removeDyingProviderLocked depends on provider cpr.name in dying proc processName

1.3 主动杀进程

|方法|reason|含义|

top Created with Sketch.