ActivityThread是Activity里一个很重要的成员变量,俗称UI线程,也即应用的主线程,它自身有三个比较关键的成员变量,其中之一是ApplicationThread,在ActivityThread创建的时候作为全局变量被创建:
1 2 3 4 final ApplicationThread mAppThread = new ApplicationThread(); final ApplicationThread mAppThread = new ApplicationThread(); final Looper mLooper = Looper.myLooper(); final H mH = new H();
ApplicationThread是ActivityThread里一个内部类,继承自ApplicationThreadNative,而ApplicationThreadNative又继承自Binder并implements 了IApplicationThread接口(此处并没有真正实现),IApplicationThread继承IInterface,定义了一系列操作应用的接口,用来和AMS进行通信,其中和Activity生命周期相关的几个关键函数如下:
1 2 3 4 5 6 void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving,int configChanges, boolean dontReport) throws RemoteException; void scheduleStopActivity(IBinder token, boolean showWindow,int configChanges) throws RemoteException; void scheduleResumeActivity(IBinder token, int procState, boolean isForward, Bundle resumeArgs)throws RemoteException;
IInterface.java代码如下:
1 2 3 4 5 6 7 8 9 public interface IInterface { /** * Retrieve the Binder object associated with this interface. * You must use this instead of a plain cast, so that proxy objects * can return the correct result. */ public IBinder asBinder(); }
Binder.java实现了IBinder接口,核心的onTransact函数和transact代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { if (code == INTERFACE_TRANSACTION) { reply.writeString(getInterfaceDescriptor()); return true; } else if (code == DUMP_TRANSACTION) { ParcelFileDescriptor fd = data.readFileDescriptor(); String[] args = data.readStringArray(); if (fd != null) { try { dump(fd.getFileDescriptor(), args); } finally { IoUtils.closeQuietly(fd); } } ........
1 2 3 4 5 6 7 8 9 10 11 12 13 public final boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { if (false) Log.v("Binder", "Transact: " + code + " to " + this); if (data != null) { data.setDataPosition(0); } boolean r = onTransact(code, data, reply, flags); if (reply != null) { reply.setDataPosition(0); } return r; }
注意上面的transact()函数是final 修饰,不可被子类重写,但onTransact()可以被重写。ApplicationThreadNative的主要功能就是重写了onTransact函数,根据不同的code路由给内部类ApplicationThreadProxy(实现了IApplicationThread接口),完成和binder通讯的部分. 也即真正实现IApplicationThread接口的有两个类:ApplicationThread和ApplicationThreadProxy,其中ApplicationThread负责通过ActivityThread最终控制Activity的生命周期,ApplicationThreadProxy负责对应功能与Binder通讯的部门。 也可以说ApplicationThread具有上面两部分功能,只不过按层次实现在不同类里.
以schedulePauseActivity()接口为例,ApplicationThreadProxy实现为:
1 2 3 4 5 6 7 8 9 10 11 12 13 public final void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges, boolean dontReport) throws RemoteException { Parcel data = Parcel.obtain(); data.writeInterfaceToken(IApplicationThread.descriptor); data.writeStrongBinder(token); data.writeInt(finished ? 1 : 0); data.writeInt(userLeaving ? 1 :0); data.writeInt(configChanges); data.writeInt(dontReport ? 1 : 0); mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null, IBinder.FLAG_ONEWAY); data.recycle(); }
ApplicationThread对其实现为:
1 2 3 4 5 6 7 8 9 10 11 12 13 public final void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges, boolean dontReport) { int seq = getLifecycleSeq(); if (DEBUG_ORDER) Slog.d(TAG, "pauseActivity " + ActivityThread.this + " operation received seq: " + seq); sendMessage( finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY, token, (userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0), configChanges, seq); }
其中sendMessage实现为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) { if (DEBUG_MESSAGES) Slog.v( TAG, "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj); Message msg = Message.obtain(); msg.what = what; msg.obj = obj; msg.arg1 = arg1; msg.arg2 = arg2; if (async) { msg.setAsynchronous(true); } mH.sendMessage(msg); }
mH继承自Handler负责处理ApplicationThread发送到消息队列的消息,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 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; .........
上面把ActivityThread、ApplicationThread、ApplicationThreadProxy、ApplicationThreadNative的关系说清楚了,下面接着看流程.
step3–Instrumentation.execStartActivity Instrumentation里的execStartActivity()核心代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; Uri referrer = target != null ? target.onProvideReferrer() : null; ......... 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; }
最关键的是int result = ActivityManagerNative.getDefault().startActivity(...),ActivityManagerNative在路径:/frameworks/base/core/java/android/app/ActivityManagerNative.java,其中的getDefault()函数返回内部的变量:gDefault:
1 2 3 4 5 6 7 8 9 10 11 12 13 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; } }
ServiceManager路径/frameworks/base/core/java/android/os/ServiceManager.java,它就是Android的ServiceManager进程,本身也是一个服务,内部通过一个HashMap类型sCache变量保存各种Service的Binder接口,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 private static HashMap<String, IBinder> sCache = new HashMap<String, IBinder>(); public static IBinder getService(String name) { try { IBinder service = sCache.get(name); if (service != null) { return service; } else { return getIServiceManager().getService(name); } ......... } public static void addService(String name, IBinder service) { try { getIServiceManager().addService(name, service, false); } catch (RemoteException e) { Log.e(TAG, "error in addService", e); } }
从中可以看到gDefault实质是ActivityManagerService的远程接口,然后通过asInterface这个函数将一个Binder对象转为IActivityManager接口,并生成了一个ActivityManagerProxy对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 /** * Cast a Binder object into an activity manager interface, generating * a proxy if needed. */ static public IActivityManager asInterface(IBinder obj) { if (obj == null) { return null; } IActivityManager in = (IActivityManager)obj.queryLocalInterface(descriptor); if (in != null) { return in; } return new ActivityManagerProxy(obj); }
所以最终又调到了ActivityManagerProxy.startActivity函数. 这里ActivityManagerNative和ActivityManagerProxy,与ApplicationThreadNative和ApplicationThreadProxy在实现模式上是一样的。
step4–ActivityManagerProxy.startActivity 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class ActivityManagerProxy implements IActivityManager { public ActivityManagerProxy(IBinder remote) { mRemote = remote; } 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.obtain(); Parcel reply = Parcel.obtain(); data.writeInterfaceToken(IActivityManager.descriptor); data.writeStrongBinder(caller != null ? caller.asBinder() : null); ......data.writeString(callingPackage); intent.writeToParcel(data, 0); ... mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0); reply.readException(); int result = reply.readInt(); reply.recycle(); data.recycle(); return result; }
上面说过在ActivityManagerProxy被创建的时候传进来一个IBinder对象,这个就是AMS的远程调用接口,也即mRemote变量.这里最核心的一句是:mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0)。
step4–ActivityManagerService.startActivity 上个步骤里的mRemote.transact()就是利用binder驱动进行跨进程通信的过程,在mRemote的onTransact函数里一定有个地方去响应START_ACTIVITY_TRANSACTION这个命令。
注意:上面的步骤都是在初始应用程序A进程里,在onTransact时来到了AMS,也即AMS所在的SystemServer进程.
我们直接到ActivityManagerService里去找. 源码在/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java,它继承了上面的ActivityManagerNative,在其onTransact函数里找到:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { switch (code) { case START_ACTIVITY_TRANSACTION: { data.enforceInterface(IActivityManager.descriptor); IBinder b = data.readStrongBinder(); IApplicationThread app = ApplicationThreadNative.asInterface(b); String callingPackage = data.readString(); ............. int result = startActivity(........); reply.writeNoException(); reply.writeInt(result); return true; }
这里又调用了startActivity函数,但是ActivityManagerNative是个abstract类,并没有真正实现IActivityManager接口,其实现在其子类ActivityManagerService里。它又调了内部的startActivityAsUser()函数,最终又进到mActivityStarter.startActivityMayWait()函数里。
step5–ActivityStarter.startActivityMayWait 备注:此处往下的流程集中在ActivityStackSupervisor、ActivityStack、ActivityStarter比较复杂,只交代调用流程,不作太多解释. startActivityMayWait()这个函数比较长,最终又调了内部的startActivityLocked里。 doPendingActivityLaunchesLocked—startActivityUnchecked,在startActivityUnchecked通过mSupervisor.resumeFocusedStackTopActivityLocked(),进到ActivityStackSupervisor,然后进到ActivityStack.resumeTopActivityUncheckedLocked,再调内部的resumeTopActivityInnerLocked()函数,再调内部的startPausingLocked函数,其中关键一句:
1 2 3 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing, userLeaving, prev.configChangeFlags, dontWait);
这里prev类型为ActivityRecord,app类型为ProcessRecord,thread类型为IApplicationThread,即prev.app.thread是运行在ActivityManagerService进程里的``ApplicationThread的远程调用接口ApplicationThreadProxy`.
step6–ApplicationThreadProxy.schedulePauseActivity 代码如下:
1 2 3 4 5 6 7 8 9 boolean userLeaving, int configChanges, boolean dontReport) throws RemoteException { Parcel data = Parcel.obtain(); data.writeInterfaceToken(IApplicationThread.descriptor); .......... data.writeInt(dontReport ? 1 : 0); mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null, IBinder.FLAG_ONEWAY); data.recycle(); }
通过进程间通信,来到ApplicationThreadNative里的onTransact函数:
1 2 3 4 5 6 7 8 9 10 11 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { switch (code) { case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION: { data.enforceInterface(IApplicationThread.descriptor); IBinder b = data.readStrongBinder(); ...... schedulePauseActivity(b, finished, userLeaving, configChanges, dontReport); return true; }
step7–ApplicationThread.schedulePauseActivity 注意:经过上面步骤里的onTransact来到了Launcher进程里. schedulePauseActivity()通过ActivityThread里的HandlermH,将消息转发至UI线程里。
1 2 3 4 5 6 7 8 9 case PAUSE_ACTIVITY: { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause"); SomeArgs args = (SomeArgs) msg.obj; handlePauseActivity((IBinder) args.arg1, false, (args.argi1 & USER_LEAVING) != 0, args.argi2, (args.argi1 & DONT_REPORT) != 0, args.argi3); maybeSnapshot(); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); } break;
进到了handlePauseActivity():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 private void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges, boolean dontReport, int seq) { ActivityClientRecord r = mActivities.get(token); if (r != null) { performPauseActivity(token, finished, r.isPreHoneycomb(), "handlePauseActivity"); // Tell the activity manager we have paused. if (!dontReport) { try { ActivityManagerNative.getDefault().activityPaused(token); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } mSomeActivitiesChanged = true; } }
函数首先将Binder引用token转换成ActivityRecord的远程接口ActivityClientRecord,然后做了三个事情:
如果userLeaving为true,则通过调用performUserLeavingActivity函数来调用Activity.onUserLeaveHint通知Activity,用户要离开它了;
调用performPauseActivity函数来调用Activity.onPause函数,我们知道,在Activity的生命周期中,当它要让位于其它的Activity时,系统就会调用它的onPause函数;
它通知ActivityManagerService,这个Activity已经进入Paused状态了,ActivityManagerService现在可以完成未竟的事情,即启动MainActivity了。ActivityManagerProxy里activityPaused函数如下:1 2 3 4 5 6 7 8 9 10 11 public void activityPaused(IBinder token) throws RemoteException { Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); data.writeInterfaceToken(IActivityManager.descriptor); data.writeStrongBinder(token); mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0); reply.readException(); data.recycle(); reply.recycle(); }
step8–ActivityManagerService.activityPaused
备注:又来到了AMS所在的进程!!! 上面的步骤经过进程间通信来到ActivityManagerNative里的:
1 2 3 4 5 6 7 case ACTIVITY_PAUSED_TRANSACTION: { data.enforceInterface(IActivityManager.descriptor); IBinder token = data.readStrongBinder(); activityPaused(token); reply.writeNoException(); return true; }
调到AMS的activityPaused()函数。
1 2 3 4 5 6 7 8 9 10 public final void activityPaused(IBinder token) { final long origId = Binder.clearCallingIdentity(); synchronized(this) { ActivityStack stack = ActivityRecord.getStackLocked(token); if (stack != null) { stack.activityPausedLocked(token, false); } } Binder.restoreCallingIdentity(origId); }
step9–ActivityStack.activityPausedLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 final void activityPausedLocked(IBinder token, boolean timeout) { if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Activity paused: token=" + token + ", timeout=" + timeout); final ActivityRecord r = isInStackLocked(token); if (r != null) { mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r); if (mPausingActivity == r) { if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r + (timeout ? " (due to timeout)" : " (pause complete)")); completePauseLocked(true, null); return; }
调到了内部函数completePauseLocked():
1 2 3 4 5 6 7 8 9 10 11 completePauseLocked(){ ....... if (resumeNext) { final ActivityStack topStack = mStackSupervisor.getFocusedStack(); if (!mService.isSleepingOrShuttingDownLocked()) { mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null); } } } ...... }
最终调了ActivityStackSupervisor里的resumeFocusedStackTopActivityLocked函数.
step10–ActivityStackSupervisor.resumeFocusedStackTopActivityLocked 通过之前流程可以知道,当前在堆栈顶端的Activity为我们即将要启动的Activity,而Launcher对应的Activity已经被paused了。
1 2 3 4 5 6 7 8 9 10 11 boolean resumeFocusedStackTopActivityLocked( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) { if (targetStack != null && isFocusedStack(targetStack)) { return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); } final ActivityRecord r = mFocusedStack.topRunningActivityLocked(); if (r == null || r.state != RESUMED) { mFocusedStack.resumeTopActivityUncheckedLocked(null, null); } return false; }
然后调用ActivityStack的resumeTopActivityUncheckedLocked()函数.
step10–ActivityStack.resumeTopActivityUncheckedLocked 在resumeTopActivityUncheckedLocked函数里调了自身的resumeTopActivityInnerLocked,然后调自身的resumeTopActivityInnerLocked,最终调了mStackSupervisor.startSpecificActivityLocked(next, true, true).
step11–ActivityStackSupervisor.startSpecificActivityLocked 1 2 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false, true);
调到了ActivityManagerService里.
step12–ActivityManagerService.startProcessLocked 此函数里核心代码如下:
1 2 3 4 5 6 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!");
step13–Process.start() 最终来到了Process(./frameworks/base/core/java/android/os/Process.java),调用自身startViaZygote(),在这个函数里最后一句是:
1 return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
首先通过openZygoteSocketIfNeeded,建AMS进程和Zygote进程通过socket进行跨进程通信的连接. 然后zygoteSendArgsAndGetResult()这个函数向zygote进程发送一个参数列表,zygote进程会启动一个新的子进程并返回该子进程的pid号。 请求的参数中有一个字符串,它的值是“android.app.ActivityThread”。现在该回到zygote处理请求那块去看看了——就是runSelectLoop函数,具体在ZygoteInit里:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 private static void runSelectLoop(String abiList) throws MethodAndArgsCaller { ......... while (true) { StructPollfd[] pollFds = new StructPollfd[fds.size()]; for (int i = 0; i < pollFds.length; ++i) { pollFds[i] = new StructPollfd(); pollFds[i].fd = fds.get(i); pollFds[i].events = (short) POLLIN; } try { Os.poll(pollFds, -1); } catch (ErrnoException ex) { throw new RuntimeException("poll failed", ex); } for (int i = pollFds.length - 1; i >= 0; --i) { if ((pollFds[i].revents & POLLIN) == 0) { continue; } if (i == 0) { ZygoteConnection newPeer = acceptCommandPeer(abiList); peers.add(newPeer); fds.add(newPeer.getFileDesciptor()); } else { boolean done = peers.get(i).runOnce(); if (done) { peers.remove(i); fds.remove(i); } } } } }
可以看到里面是一个while循环,一直在监听socket发来的信息,最终调用了ZygoteConnection里的runOnce函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 boolean runOnce() throws ZygoteInit.MethodAndArgsCaller { pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo, parsedArgs.niceName, fdsToClose, parsedArgs.instructionSet, parsedArgs.appDataDir); } ....... if (pid == 0) { // in child IoUtils.closeQuietly(serverPipeFd); serverPipeFd = null; handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr); // should never get here, the child is expected to either // throw ZygoteInit.MethodAndArgsCaller or exec(). return true; }
这里最终调到了Zygote的两个关键函数forkAndSpecialize函数,然后通过JNI调用了nativeForkAndSpecialize函数,这个函数最终fork了一个子进程,暂时忽略. 另外一个函数是handleChildProc():
1 2 3 4 5 6 7 8 9 10 if (parsedArgs.invokeWith != null) { WrapperInit.execApplication(parsedArgs.invokeWith, parsedArgs.niceName, parsedArgs.targetSdkVersion, VMRuntime.getCurrentInstructionSet(), pipeFd, parsedArgs.remainingArgs); } else { RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, null /* classLoader */); }
这里会走到RuntimeInit.zygoteInit,然后调内部的applicationInit()函数,再调内部的invokeStaticMain()函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { Class<?> cl; try { cl = Class.forName(className, true, classLoader); } ...... Method m; try { m = cl.getMethod("main", new Class[] { String[].class }); } catch (NoSuchMethodException ex) { throw new RuntimeException( "Missing static main on " + className, ex); } ...... }
可以看到,上述代码完成了一个反射的功能,去加载传进来的类名的main方法。在打开应用过程中,这个类名就是android.app.ActivityThread
step14–ActivityThread.main() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public static void main(String[] args) { SamplingProfilerIntegration.start(); ...... Process.setArgV0("<pre-initialized>"); Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } .....
在main函数里,创建了ActivityThread和主Ui线程Handler,然后调用它的attach函数:
1 2 3 4 5 6 final IActivityManager mgr = ActivityManagerNative.getDefault(); try { mgr.attachApplication(mAppThread); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); }
这里mgr就是ActivityManagerService的远程接口ActivityManagerProxy的attachApplication函数.
1 2 3 4 5 6 7 8 9 10 11 public void attachApplication(IApplicationThread app) throws RemoteException { Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); data.writeInterfaceToken(IActivityManager.descriptor); data.writeStrongBinder(app.asBinder()); mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0); reply.readException(); data.recycle(); reply.recycle(); }
这里传进来的参数就是刚刚创建进程的远程调用接口,将其传给AMS。通过跨进程通讯,来到了ActivityManagerService的attachApplication函数。
step15–ActivityManagerService.attachApplication() 1 2 3 4 5 6 7 8 9 10 if (normalMode) { try { if (mStackSupervisor.attachApplicationLocked(app)) { didSomething = true; } } catch (Exception e) { Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); badApp = true; } }
这里进到了attachApplicationLocked函数.
step16–ActivityStackSupervisor.attachApplicationLocked() 1 2 3 4 5 6 7 8 ActivityRecord hr = stack.topRunningActivityLocked(); if (hr != null) { if (hr.app == null && app.uid == hr.info.applicationInfo.uid && processName.equals(hr.processName)) { try { if (realStartActivityLocked(hr, app, true, true)) { didSomething = true; .....
这里先调ActivityStack的topRunningActivityLocked,然后再调自己的realStartActivityLocked:
1 2 3 4 5 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);
这里app.thread最终进到了ApplicationThreadProxy的scheduleLaunchActivity函数中。
step17–ApplicationThreadProxy.scheduleLaunchActivity() 1 2 mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null, IBinder.FLAG_ONEWAY);
AMS通过Binder通信,告诉SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION,进到了scheduleLaunchActivity
step18–ApplicationThreadProxy.scheduleLaunchActivity() 1 2 3 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident...) sendMessage(H.LAUNCH_ACTIVITY, r); }
来到了Handler(H)的handleMessage函数里:
1 2 3 4 5 6 7 8 9 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;
调用自己的handleLaunchActivity:
1 2 3 4 5 6 7 8 9 private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) { ...... Activity a = performLaunchActivity(r, customIntent); if (a != null) { ..... handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason); .... performPauseActivityIfNeeded(r, reason);
在handleLaunchActivity函数里主要干了两个重要事情,第一是通过performLaunchActivity去加载一个Activity,然后调用它的onCreate方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ......... if (r.activityInfo.targetActivity != null) { component = new ComponentName(r.activityInfo.packageName, r.activityInfo.targetActivity); } Activity activity = null; try { java.lang.ClassLoader cl = r.packageInfo.getClassLoader(); activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); } ..... try { Application app = r.packageInfo.makeApplication(false, mInstrumentation); .... if (activity != null) { Context appContext = createBaseContextForActivity(r, activity); CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); Configuration config = new Configuration(mCompatConfiguration); .... activity.attach(appContext, this, getInstrumentation(), r) .... if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); }
在performLaunchActivity函数里,先通过类加载器创建一个Activity对象,然后创建Application对象,调用Activity的attach(),再通过mInstrumentation.callActivityOnCreate调Activity的onCreate。然后回到handleLaunchActivity函数,执行handleResumeActivity,即调Activity的onResume()生命周期。终于,新打开的Activity启动起来了!!!
过程总结 整个应用程序的启动过程要执行很多步骤,但是整体来看,主要分为以下五个阶段:
Launcher通过Binder进程间通信机制通知AMS,它要启动一个Activity;
AMS通过Binder进程间通信机制通知Launcher进入Paused状态;
Launcher通过Binder进程间通信机制通知AMS它已经准备就绪进入Paused状态,于是AMS就创建一个新的进程,用来启动一个ActivityThread实例,即将要启动的Activity就是在这个ActivityThread实例中运行;
ActivityThread通过Binder进程间通信机制将一个ApplicationThread类型的Binder对象传递给AMS,以便以后AMS能够通过这个Binder对象和它进行通信;
AMS通过Binder进程间通信机制通知ActivityThread,现在一切准备就绪,它可以真正执行Activity的启动操作了。
调用流程图