一. 应用程序进程启动过程
应用程序进程
- 要想启动一个应用程序,首先要保证这个应用程序所需要的应用程序进程已经被启动。
- ActivityManagerService在启动应用程序时会检查这个应用程序需要的应用程序进程是否存在,不存在就会请求Zygote进程将需要的应用程序进程启动,对应上一篇的系统启动流程->Zygote启动过程中的:
public static void main(String argv[]) {
...
try {
...
registerZygoteSocket(socketName);
...
preload();
...
if (startSystemServer) {
startSystemServer(abiList, socketName);
}
Log.i(TAG, "Accepting command socket connections");
runSelectLoop(abiList);
closeServerSocket();
} catch (MethodAndArgsCaller caller) {
caller.run();
} catch (RuntimeException ex) {
Log.e(TAG, "Zygote died with exception", ex);
closeServerSocket();
throw ex;
}
}
- Zygote进程通过fork自身创建的应用程序进程,这样应用程序程序进程就会获得Zygote进程在启动时创建的虚拟机实例,还可以获得Binder线程池和消息循环,这样运行在应用进程中的应用程序就可以方便的使用Binder进行进程间通信以及消息处理机制了。
应用程序进程创建过程
1.AMS向Zygote进程发送创建应用程序进程请求:
- 调用ActivityManagerService的startProcessLocked函数发送创建应用程序进程请求
- 调用ZygoteState的connect函数与Socket建立连接
调用ZygoteState的connect函数与名称为ZYGOTE_SOCKET(值为“zygote”)的Socket建立连接。
如果连接返回的primaryZygoteState与当前的abi不匹配,则会连接name为“zygote_secondary”的Socket。
两个Socket区别:name为”zygote”的Socket是运行在64位Zygote进程中的,而name为“zygote_secondary”的Socket则运行
在32位Zygote进程中。既然应用程序进程是通过Zygote进程fork产生的,当要连接Zygote中的Socket时,也需要保证位数的一致。
2.Zygote进程接收请求并创建应用程序进程
- ZygoteInit.main()中调用ZygoteInit.runSelectLoop()等待ActivityManagerService的请求;
- ZygoteInit.runSelectLoop()中调用ZygoteConnection.runOnce()来处理请求的数据:
- ZygoteConnection.runOnce()中调用Zygote的forkAndSpecialize函数来创建应用程序进程,主要是通过fork当前进程来创建一个子进程,如果返回的pid等于0,则说明是在新创建的子进程中执行的,则调用ZygoteConnection的handleChildProc函数来启动应用程序进程;
- ZygoteConnection.handleChildProc()中调用RuntimeInit.zygoteInit()
- RuntimeInit.zygoteInit()中创建Binder线程池,并调用了applicationInit(),applicationInit()中又调用invokeStaticMain(),
public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "RuntimeInit");
redirectLogStreams();
commonInit();
nativeZygoteInit();
applicationInit(targetSdkVersion, argv, classLoader);
}
- RuntimeInit.invokeStaticMain()中通过反射来获得android.app.ActivityThread类,并获得ActivityThread的main函数,再将main函数传入到ZygoteInit中的MethodAndArgsCaller类的构造函数中,MethodAndArgsCaller类内部会通过反射调用ActivityThread的main函数,到这里,应用程序进程就创建完成了并且运行了代表主线程的实例ActivityThread,代码如下
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Missing static main on " + className, ex);
}
...
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
3.Binder线程池启动过程
- 上面提到了RuntimeInit.zygoteInit()中调用nativeZygoteInit()创建Binder线程池,nativeZygoteInit是一个jni方法,代码如下
static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz){
gCurRuntime->onZygoteInit();
}
- nativeZygoteInit()中调用了onZygoteInit(),onZygoteInit()方法在app_main.cpp中,代码如下
virtual void onZygoteInit(){
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool();
}
- onZygoteInit()中又调用了startThreadPool(),其代码如下
void ProcessState::startThreadPool(){
AutoMutex _l(mLock);
if (!mThreadPoolStarted) {
mThreadPoolStarted = true;
spawnPooledThread(true);
}
}
void ProcessState::spawnPooledThread(bool isMain){
if (mThreadPoolStarted) {
String8 name = makeBinderThreadName();
ALOGV("Spawning new pooled thread, name=%s\n", name.string());
sp<Thread> t = new PoolThread(isMain);
t->run(name.string());
}
}
- PoolThread类继承了Thread类, 其中调用IPCThreadState.joinThreadPool()将当前线程注册到Binder驱动程序中,这样我们创建的线程就加入了Binder线程池中,新创建的应用程序进程就支持Binder进程间通信了;
class PoolThread : public Thread{
..
protected:
virtual bool threadLoop()
{
IPCThreadState::self()->joinThreadPool(mIsMain);
return false;
}
const bool mIsMain;
};
4.消息循环创建过程
- 上面2中提到RuntimeInit.invokeStaticMain()中通过throw new ZygoteInit.MethodAndArgsCaller,抛出一个MethodAndArgsCaller异常,这个异常会被ZygoteInit的main函数捕获,捕获到会执行caller的run函数
public static void main(String argv[]) {
...
try {
...
} catch (MethodAndArgsCaller caller) {
caller.run();
} catch (RuntimeException ex) {
Log.e(TAG, "Zygote died with exception", ex);
closeServerSocket();
throw ex;
}
}
public static class MethodAndArgsCaller extends Exception
implements Runnable {
private final Method mMethod;
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
public void run() {
try {
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
...
throw new RuntimeException(ex);
}
}
}
- ActivityThread.main()代码如下,系统在应用程序进程启动完成后,就会创建一个消息循环,用来方便的使用Android的消息处理机制
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
SamplingProfilerIntegration.start();
...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
二. 应用程序启动过程
- 分析应用程序的启动过程其实就是分析根Activity的启动过程
1.Launcher请求ActivityManageService
- Launcher启动后会将已安装应用程序的快捷图标显示到界面上,点击时就会调用Launcher.startActivitySafely()
public boolean startActivitySafely(View v, Intent intent, Object tag) {
...
try {
success = startActivity(v, intent, tag);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
}
return success;
}
- startActivitySafely又调用Launcher.startActivity(),Launcher.startActivity()中设置Flag为FLAG_ACTIVITY_NEW_TASK,让根Activity在新的任务栈中启动,然后调用Activity.startActivity()
private boolean startActivity(View v, Intent intent, Object tag) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
...
if (user == null || user.equals(UserHandleCompat.myUserHandle())) {
StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy();
try {
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog().build());
startActivity(intent, optsBundle);
} finally {
StrictMode.setVmPolicy(oldPolicy);
}
} else {
launcherApps.startActivityForProfile(intent.getComponent(), user,
intent.getSourceBounds(), optsBundle);
}
return true;
} catch (SecurityException e) {
...
}
return false;
}
- startActivity()最终调用startActivityForResult函数,其中第二个参数为-1,表示Launcher不需要知道Activity启动的结果;
Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
- startActivityForResult中,因为目前根Activity还没有创建出来,mParent == null成立,于是调用execStartActivity
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
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);
}
}
}
- Instrumentation.execStartActivity代码如下,调用ActivityManagerNative的getDefault来获取ActivityManageService,接着调用它的startActivity方法
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
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;
}
- ActivityManagerNative.getDefault()代码如下
static public IActivityManager getDefault() {
return gDefault.get();
}
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
if (false) {
Log.v("ActivityManager", "default service binder = " + b);
}
IActivityManager am = asInterface(b);
if (false) {
Log.v("ActivityManager", "default service = " + am);
}
return am;
}
};
- execStartActivity方法中,从getDefault得知就是调用AMP的startActivity,其中AMP是ActivityManagerNative的内部类,代码如下所示
public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
//将传入的参数写入到Parcel类型的data中
Parcel data = Parcel.obtain()
Parcel reply = Parcel.obtain()
data.writeInterfaceToken(IActivityManager.descriptor)
data.writeStrongBinder(caller != null ? caller.asBinder() : null)
data.writeString(callingPackage)
intent.writeToParcel(data, 0)
data.writeString(resolvedType)
data.writeStrongBinder(resultTo)
data.writeString(resultWho)
data.writeInt(requestCode)
data.writeInt(startFlags)
if (profilerInfo != null) {
data.writeInt(1)
profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE)
} else {
data.writeInt(0)
}
if (options != null) {
data.writeInt(1)
options.writeToParcel(data, 0)
} else {
data.writeInt(0)
}
//通过IBinder对象向AMS发送进程间通信请求
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0)
reply.readException()
int result = reply.readInt()
reply.recycle()
data.recycle()
return result
}
- 通过IBinder类型对象mRemote向AMS发送一个START_ACTIVITY_TRANSACTION类型的进程间通信请求, 那么服务端AMS就会从Binder线程池中读取我们客户端发来的数据,最终会调用ActivityManagerNative的onTransact方法中执行
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
case START_ACTIVITY_TRANSACTION:
{
...
int result = startActivity(app, callingPackage, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
reply.writeNoException();
reply.writeInt(result);
return true;
}
}
- onTransact中会调用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 bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
2.ActivityManageService到ApplicationThread的调用流程
- ActivityManageService.startActivity()中return startActivityAsUser():
- startActivityAsUser()中return ActivityStarter.startActivityMayWait();
- startActivityMayWait()调用ActivityStarter.startActivityLocked();
- startActivityLocked()调用ActivityStarter.doPendingActivityLaunchesLocked(false);
- doPendingActivityLaunchesLocked调用ActivityStarter.startActivityUnchecked();
- startActivityUnchecked()调用ActivityStackSupervisor.resumeFocusedStackTopActivityLocked();
- resumeFocusedStackTopActivityLocked()调用ActivityStack.resumeTopActivityUncheckedLocked();
- resumeTopActivityUncheckedLocked()调用ActivityStack.resumeTopActivityInnerLocked()
- resumeTopActivityInnerLocked调用ActivityStackSupervisor.startSpecificActivityLocked()
- startSpecificActivityLocked调用ActivityStackSupervisor.realStartActivityLocked()
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
...
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
...
return true;
}
- 上面的 app.thread指的是IApplicationThread,它的实现是ActivityThread的内部类ApplicationThread,其中ApplicationThread继承了ApplicationThreadNative,而ApplicationThreadNative继承了Binder并实现了IApplicationThread接口。
3.ActivityThread启动Activity
- 上面ActivityManageService到ApplicationThread的调用流程的最后来到了ApplicationThread的scheduleLaunchActivity(),其代码如下
@Override
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
updateProcessState(procState, false)
ActivityClientRecord r = new ActivityClientRecord()
r.token = token
r.ident = ident
r.intent = intent
r.referrer = referrer
r.voiceInteractor = voiceInteractor
r.activityInfo = info
r.compatInfo = compatInfo
r.state = state
r.persistentState = persistentState
r.pendingResults = pendingResults
r.pendingIntents = pendingNewIntents
r.startsNotResumed = notResumed
r.isForward = isForward
r.profilerInfo = profilerInfo
r.overrideConfig = overrideConfig
updatePendingConfiguration(curConfig)
sendMessage(H.LAUNCH_ACTIVITY, r)
}
- scheduleLaunchActivity()将启动Activity的参数封装成ActivityClientRecord,然后调用了ActivityThread.sendMessage(),向H类发送类型为LAUNCH_ACTIVITY的消息,并将ActivityClientRecord 传递过去;
- 其中H是ActivityThread的内部类并继承Handler,代码如下
private class H extends Handler {
public static final int LAUNCH_ACTIVITY = 100;
public static final int PAUSE_ACTIVITY = 101;
...
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
case RELAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
handleRelaunchActivity(r);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
...
}
- handleMessage()中调用了ActivityThread.handleLaunchActivity():
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
...
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
reportSizeConfigurations(r);
Bundle oldState = r.state;
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
if (!r.activity.mFinished && r.startsNotResumed) {
performPauseActivityIfNeeded(r, reason);
if (r.isPreHoneycomb()) {
r.state = oldState;
}
}
} else {
try {
ActivityManagerNative.getDefault()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
}
- 上面handleLaunchActivity()调用了ActivityThread.performLaunchActivity()
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
ActivityInfo aInfo = r.activityInfo
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE)
}
//获取要启动的Activity的ComponentName类,ComponentName类中保存了该Activity的包名和类名
ComponentName component = r.intent.getComponent()
...
Activity activity = null
try {
//根据ComponentName中存储的Activity类名,用类加载器来创建该Activity的实例
java.lang.ClassLoader cl = r.packageInfo.getClassLoader()
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent)
...
}
} catch (Exception e) {
...
}
try {
//创建Application,makeApplication方法内部会调用Application的onCreate方法
Application app = r.packageInfo.makeApplication(false, mInstrumentation)
...
if (activity != null) {
//创建要启动Activity的上下文环境
Context appContext = createBaseContextForActivity(r, activity)
...
}
//调用Activity的attach方法初始化Activity,attach方法中会创建Window对象(PhoneWindow)并与Activity自身进行关联
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window)
...
if (r.isPersistable()) {
//调用Instrumentation的callActivityOnCreate方法来启动Activity
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState)
} else {
mInstrumentation.callActivityOnCreate(activity, r.state)
}
...
}
return activity
}
- performLaunchActivity中调用了Activity的performCreate()
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}
- performCreate方法中会调用Activity的onCreate方法,这样Activity就启动了,即应用程序就启动了
final void performCreate(Bundle icicle) {
restoreHasCurrentPermissionRequest(icicle);
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
我是今阳,如果想要进阶和了解更多的干货,欢迎关注微信公众号 “今阳说” 接收我的最新文章