Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 源码解析(十一):应用进程启动流程详解

編輯:關於 Android 開發

Android 源码解析(十一):应用进程启动流程详解

在 Android 官方指南中,有这样一段关于应用进程的描述:

By default, every application runs in its own Linux process. Android starts the process when any of the application's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other applications.

意思是:每个 Android 应用默认都在自己的 Linux 进程中运行。当应用中某个组件需要被执行时,系统会启动这个进程;而当进程不再需要,或系统需要为其他应用回收内存时,就会杀掉它。因此,当我们启动四大组件之一时,如果该应用的进程尚未启动,系统会先启动这个进程。

本节主要通过分析 Activity 的启动过程,介绍应用进程的启动流程。

上一篇文章简要介绍了 Launcher 的启动流程:在 SystemServer 进程执行完成、各种系统服务启动完成后,会调用 ActivityManagerService 的 systemReady() 方法,其中就包含了启动 Launcher 的相关逻辑。

Launcher 在启动过程中,会通过 PackageManagerService 查询系统中所有已安装应用的包名、图标和名称等信息,填充到 Launcher 的 Adapter 中。这样点击某个应用图标时,就能根据该图标的包名和启动 Activity 的类名初始化 Intent,再调用 startActivity(Intent) 启动对应应用。

其实 Android 中应用进程可以通过多种方式启动,比如启动 Activity、Service、ContentProvider 或 BroadcastReceiver,也就是通过启动四大组件来触发。当这些组件需要运行而对应进程尚未启动时,系统就会判断并启动该进程。

这里我们通过 Launcher 简单分析一下应用进程的启动流程。每个 Launcher 图标对应一个应用包名和启动 Activity 类名,查看 LauncherActivity 中的图标点击事件:

protected void onListItemClick(ListView l, View v, int position, long id) {
    Intent intent = intentForPosition(position);
    startActivity(intent);
}

用包名和启动 Activity 类名构造好 Intent 后,调用 startActivity 启动 Activity。很明显,此时应用尚未启动,也就是说 startActivity 不仅启动了 Activity,还在启动它之前拉起了应用进程。我们就以这个方法为入口来分析。

跟踪代码到 Activity,发现它调用了 startActivity 的重载方法:

@Override
public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        startActivityForResult(intent, -1);
    }
}

由于传入的 options 为空,最终调用:

public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
    if (mParent == null) {
        Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        if (ar != null) {
            mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode,
                    ar.getResultCode(), ar.getResultData());
        }
        if (requestCode >= 0) {
            mStartedActivity = true;
        }
        cancelInputsAndStartExitTransition(options);
    } else {
        if (options != null) {
            mParent.startActivityFromChild(this, intent, requestCode, options);
        } else {
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }
}

可以看到这里调用了 mInstrumentation.execStartActivity。简单介绍一下 Instrumentation:它是 Android 系统中应用端操作 Activity 的具体操作类,这里的"应用端"是相对于 ActivityManagerService 服务端而言的。也就是说,我们在执行对 Activity 的具体操作(比如回调生命周期各方法)时,都借助 Instrumentation 来实现。

下面看 Instrumentation 的 execStartActivity:

public ActivityResult execStartActivity(Context who, IBinder contextThread,
        IBinder token, Activity target, Intent intent, int requestCode, Bundle options) {
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess();
        int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

这里重点关注:

int result = ActivityManagerNative.getDefault()
        .startActivity(whoThread, who.getBasePackageName(), intent,
                intent.resolveTypeIfNeeded(who.getContentResolver()),
                token, target != null ? target.mEmbeddedID : null,
                requestCode, 0, null, options);

这实际上是进程间通信。ActivityManagerNative 继承自 Binder 接口,是一个 Binder 对象;而 ActivityManagerService 又继承自 ActivityManagerNative。了解 Binder 机制的读者就明白:AMS 是服务端,ActivityManagerNative 是客户端。因此这里调用的 startActivity 实际是把参数传给 AMS 并执行其 startActivity 方法。

看一下 AMS 的 startActivity:

@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho,
        int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType,
            resultTo, resultWho, requestCode, startFlags, profilerInfo,
            options, UserHandle.getCallingUserId());
}

调用了 startActivityAsUser:

@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho,
        int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
    enforceNotIsolatedCaller("startActivity");
    userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
            userId, false, ALLOW_FULL_ONLY, "startActivity", null);
    return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage,
            intent, resolvedType, null, null, resultTo, resultWho, requestCode,
            startFlags, profilerInfo, null, null, options, false, userId, null, null);
}

继续查看 startActivityMayWait:

final int startActivityMayWait(...) {
    int res = startActivityLocked(caller, intent, resolvedType, aInfo,
            voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
            callingPid, callingUid, callingPackage, realCallingPid, realCallingUid,
            startFlags, options, ignoreTargetSecurity, componentSpecified,
            null, container, inTask);
    return res;
}

它的逻辑较多,我们重点关注其调用了 startActivityLocked,进而调用 startActivityUncheckedLocked:

err = startActivityUncheckedLocked(r, sourceRecord, voiceSession,
        voiceInteractor, startFlags, true, options, inTask);
targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);

查看 startActivityLocked 的实现:

if (doResume) {
    mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
}
stack.resumeTopActivityLocked(null);
final boolean resumeTopActivityLocked(ActivityRecord prev) {
    return resumeTopActivityLocked(prev, null);
}
result = resumeTopActivityInnerLocked(prev, options);

继续查看 resumeTopActivityInnerLocked:

mStackSupervisor.startSpecificActivityLocked(next, true, true);

可以发现在方法体中,执行相关判断与初始化后调用了 startSpecificActivityLocked:

mService.startProcessLocked(r.processName, r.info.applicationInfo,
        true, 0, "activity", r.intent.getComponent(), false, false, true);

可以看到它调用了 startProcessLocked,从名字就能看出这个方法就是用来启动进程的。

final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
        boolean knownToBeDead, int intentFlags, String hostingType,
        ComponentName hostingName, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge) {
    return startProcessLocked(processName, info, knownToBeDead, intentFlags,
            hostingType, hostingName, allowWhileBooting, isolated, 0, null, null, null, null);
}

查看其具体实现:

checkTime(startTime, "startProcess: asking zygote to start proc");
Process.ProcessStartResult startResult = Process.start(entryPoint,
        app.processName, uid, uid, gids, debugFlags, mountExternal,
        app.info.targetSdkVersion, app.info.seinfo, requiredAbi,
        instructionSet, app.info.dataDir, entryPointArgs);
checkTime(startTime, "startProcess: returned from zygote!");

这里调用了 Process.start:

public static final ProcessStartResult start(final String processClass,
        final String niceName, int uid, int gid, int[] gids, int debugFlags,
        int mountExternal, int targetSdkVersion, String seInfo, String abi,
        String instructionSet, String appDataDir, String[] zygoteArgs) {
    try {
        return startViaZygote(processClass, niceName, uid, gid, gids,
                debugFlags, mountExternal, targetSdkVersion, seInfo, abi,
                instructionSet, appDataDir, zygoteArgs);
    } catch (ZygoteStartFailedEx ex) {
        Log.e(LOG_TAG, "Starting VM process through Zygote failed");
        throw new RuntimeException("Starting VM process through Zygote failed", ex);
    }
}

这里的 processClass 就是要启动的进程名,传入的是:

"android.app.ActivityThread"

至于 Process 启动进程的 Native 层代码这里不做过多分析。这个方法启动了 ActivityThread 进程并执行其 main 方法——所以我们常说的"进程入口是 ActivityThread 的 main 方法"正是体现在这里。

总结

1. Android 应用进程会在需要启动其组件时启动,当没有任何组件运行或系统内存较低时会被杀死。

2. 启动四大组件时,若发现应用进程未启动,会首先启动应用进程。

3. 我们可以为应用配置多个进程,每个进程都有自己的 JVM 和运行环境,进程间通信需要通过 Binder 机制。

4. Launcher 的启动也是先启动 Launcher 进程,再启动其 Activity 组件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved