Activity的启动_5.0
源码分析基于 Android 5.0.0_r2
这里分析Activity的启动,沿着思路:在一个app的已有的Activity之上,启动另外一个Activity,这两个Activity属于同一个app、同一个进程
整体流程
相关类介绍
Instrumentation
:仪表盘,具体到应用程序中是管理Activity
的一个工具类,包括创建和启动Activity
,Activity
的生命周期方法都是由Instrumentation
来控制的,一个进程只用一个Instrumentation
实例
ActivityManagerService
:Android
中最核心的服务,主要负责系统中四大组件的启动、切换、调度及应用程序的管理和调度等工作
ActivityThread
:管理应用程序进程中主线程的执行,根据Activity
管理者的请求调度和执行activities
、broadcasts
及其相关的操作
ApplicationThread
:用来实现ActivityManagerService
和ActivityThread
之间的交互
ApplicationThreadProxy
:ApplicationThread
在服务端的代理,AMS
就是通过该代理与ActivityThread
进行通信的
ActivityStack
:负责单个Activity
栈的状态和管理
ActivityStackSupervisor
:负责所有Activity栈的管理
Activity
:变量说明
mMainThread
:ActivityThread
mMainThread.getApplicationThread()
:ApplicationThread
ApplicationThread
是ActivityThread
的一个内部类,这两个类在Activity
启动的过程中都发挥着重要的作用
mMainThread实际上是ActivityThread对象,ActivityThread,就是主线程,也就是UI线程,它是在App启动时创建的,它代表了App应用程序。那Application类岂不是被架空了?其实,Application对我们App开发人员来说也许很重要,但是在Android系统中还真的没那么重要,他就是个上下文。Activity不是有个Context上下文吗?Application就是整个ActivityThread的上下文。
---摘抄自博客 Android Launcher 启动 Activity 的工作过程
startActivityForResult
调用Activity
的startActivity(XXX)
@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 {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
这里startActivity(intent,options)
无论哪种情况,最终都是调用到startActivityForResult(intent, requestCode,options)
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
if (mParent == null) {
//着重看mInstrumentation.execStartActivity(...)这一段代码
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) {
// 如果这个Activity启动需要下一个Activity的结果
// 则会在下一个Activity的结果获得之前使得这个Activity不可见。
mStartedActivity = true;
}
final View decor = mWindow != null ? mWindow.peekDecorView() : null;
if (decor != null) {
decor.cancelPendingInputEvents();
}
} else {
......
}
......
}
Activity mParent
代表的是ActivityGroup
,ActivityGroup
最开始被用来一个界面中嵌入多个子Activity
,后来在API 13
中被废弃了,使用Fragment
代替,所以这里只用看mParent == null
的逻辑
Instrumentation
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...省略ActivityMonitors相关代码
try {
...
//着重看这里的代码
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
//检查启动Activity的结果(可能会抛出异常,例如在AndroidManifest中待启动的Activity
//没有注册)
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
}
return null;
}
AMS
与IActivityManager
的关系
代码表示:
//Binder接口
public interface IActivityManager extends IInterface {...}
//Binder类,相当于Stub
public abstract class ActivityManagerNative extends Binder implements IActivityManager{.}
//Binder类的具体实现
public final class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {...}
//Binder类的本地代理,相当于Proxy,定义在ActivityManagerNative里面,不同进程下,通过 //ActivityManagerNative的asInterface,即可将AMS「继承至Stub」转化为ActivityManagerProxy //「Proxy」
class ActivityManagerProxy implements IActivityManager{...}
AIDL理解:也就是说,之前《开发艺术探索 - 第二章》中,写一个aidl
文件,就有对应的Binder接口、Stub、Proxy
,然后我们自己在远程服务端Service
自己去继承Stub
实现Binder
类「暂时称为Binder_1
」,然后本地端bindService
,将获取的Binder_1
对象,通过asInterface
的方法,转化为本地代理Proxy
。对应到这里,IActivityManager、ActivityManagerNative、ActivityManagerProxy
就相当于是aidl
文件自动生成的
Binder接口、Stub、Proxy
,只是这里它分开写了,即Binder接口
写一个,然后Stub和Proxy
写一起,这里ActivityManagerService
相当于Binder_1
关系图如下:
所以说,ActivityManagerService
简称「AMS」就是IActivityManager
的具体实现
接着看上面的execStartActivity(xxx)
,其中ActivityManagerNative.getDefault()
获取的是什么
//ActivityManagerNative中
static public IActivityManager getDefault() {
return gDefault.get();
}
//ActivityManagerNative中
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
protected IActivityManager create() {
IBinder b = ServiceManager.getService("activity");
...
IActivityManager am = asInterface(b);
...
return am;
}
};
AMS
这个Binder
对象采用单例模式对外提供,Singleton
是一个单例的封装类,第一次调用它的get
方法时,它会通过create
方法来初始化AMS
这个Binder
对象。这里获取的对象其实是一个Binder代理
,即通过ServiceManager.getService(xxx)
获取的应该是远程的Stub
类,也就是AMS
,然后通过Stub.asInterface(xxx)
,获取AMS
的代理类Proxy
,这个代理类就是ActivityManagerProxy
,简称AMP
所以上面Instrumentation
的execStartActivity(xxx)
,最终就是调用到了AMS
的startActivity(xxx)
,在这里,调用就从Instrumentation
转到了AMS
好,先岔开下话题,看Instrumentation.execStartActivity(xxx)
两个重要的参数:IBinder contextThread
和IBinder token
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {...}
IBinder contextThread
IBinder contextThread
:在Activity
中,传入的是mMainThread.getApplicationThread()
,其实就是ApplicationThread
//Binder接口
public interface IApplicationThread extends IInterface {...}
//Binder类,相当于Stub
public abstract class ApplicationThreadNative extends Binder implements IApplicationThread {}
//继承至Binder类,也就说这个相当于是Binder类的真正实现,相当于上面AMS的aidl逻辑分析中的Binder_1
private class ApplicationThread extends ApplicationThreadNative {...}
从这里看出ApplicationThread
,就是用于进程间通信的一个Binder
对象
它的本地代理对象如下,定义在ActivityThreadNative
里面,不同进程下,通过ActivityThreadNative
的asInterface
即可将ApplicationThread「继承至Stub」
转化为ApplicationThreadProxy 「Proxy」
class ApplicationThreadProxy implements IApplicationThread {...}
这一块的aidl逻辑,和上面分析的IActivityManager、ActivityManagerService那一块的aidl逻辑是一样的
IBinder token
这个token
对象其实是在Activity
的attach(xxx)
的时候传入的,也就是Activity
创建与关联的时候,它是个Binder
对象,代表了Launcher
这个Activity
,这里通过Instrumentation
传给AMS
,AMS
查询后,就知道是谁向AMS
发起请求了。Activity
的attach(xxx)
如下
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor) {..}
contextThread和token这两个参数是伏笔,传递给AMS,以后AMS想反过来通知Launcher,就能通过这两个参数,找到Launcher。
AMS.startActivity(xxx)
进程切换第一次:app进程 -> 系统进程的Binder线程池
好,回到刚刚的话题,即调用从Instrumentation
转到了AMS
,从AMS
开始,就是在远程端「系统进程」了
@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());
}
调用AMS
的startActivityAsUser(xxx)
@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, userId, null, null);
}
ActivityStack(Supervisor)
上面调用了ActivityStackSupervisor
的startActivityMayWait
,接下来的调用过程如下
1.ActivityStackSupervisor
先看一下ActivityStackSupervisor
的startActivityMayWait
final int startActivityMayWait(IApplicationThread caller, int callingUid,
String callingPackage, Intent intent, String resolvedType,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,
Bundle options, int userId, IActivityContainer iContainer, TaskRecord inTask) {
......
//根据intent在系统中找到合适的应用的activity,如果有多个activity可选择,
//则会弹出ResolverActivity让用户选择合适的应用。
ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo,userId);
......
int res = startActivityLocked(caller, intent, resolvedType, aInfo,
voiceSession, voiceInteractor, resultTo, resultWho,
requestCode, callingPid, callingUid, callingPackage,
realCallingPid, realCallingUid, startFlags, options,
componentSpecified, null, container, inTask);
return res;
}
调用到ActivityStackSupervisor
的startActivityLocked(xxx)
final int startActivityLocked(IApplicationThread caller,
Intent intent, String resolvedType, ActivityInfo aInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode,
int callingPid, int callingUid, String callingPackage,
int realCallingPid, int realCallingUid, int startFlags, Bundle options,
boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container,TaskRecord inTask) {
......
//创建ActivityRecord对象,ActivityRecord作为Activity的记录者,每次启动一个Activity
//会有一个对应的ActivityRecord对象,表示Activity的一个记录
ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,requestCode, componentSpecified, this, container, options);
......
//调用到ActivityStackSupervisor的startActivityUncheckedLocked(xxx)
//这里传入了刚刚创建的ActivityRecord r对象
err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, true, options, inTask);
}
ActivityStackSupervisor
的startActivityUncheckedLocked(xxx)
方法比较复杂,应该是对启动的flag
和启动模式等的处理,这里不深入分析,其中会调用到ActivityStack
的resumeTopActivityLocked(xxx)
方法
final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,boolean doResume, Bundle options, TaskRecord inTask) {
...
if (doResume) {
targetStack.resumeTopActivityLocked(null, options);
}
...
}
2.ActivityStack
调用到了ActivityStack
的resumeTopActivityLocked(xxx)
final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
if (inResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean result = false;
try {
// Protect against recursion.
inResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
} finally {
inResumeTopActivity = false;
}
return result;
}
调用到了ActivityStack
的resumeTopActivityInnerLocked(xxx)
final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
...
//获取要启动的Activity
ActivityRecord next = topRunningActivityLocked(null);
...
--------------------------------------------------------------------------
// 我们需要先去对当前正在显示的Activity进行onPause操作,然后要启动的Activity才能
// 进行onResume操作
boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving,true,dontWaitForPause);
//mResumedActivity的类型是ActivityRecord,指向上一次启动的Activity
if (mResumedActivity != null) {
// 通知Launcher进入pause状态
pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Pausing " + mResumedActivity);
}
--------------------------------------------------------------------------
...
//调用到了这里,这里传入了要启动的Activity的ActivityRecord
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
这里主要处理了一些Activity
栈相关的东西,主要看两部分的内容
- 让上一个
Activity
进入onPause
状态 - 调用了
ActivityStackSupervisor
的startSpecificActivityLocked(xxx)
- 先看
Activity
进入onPause状态
进程切换第二次:系统进程 -> app进程Binder线程池
先看ActivityStack
的startPausingLocked(...)
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,boolean dontWait) {
...
ActivityRecord prev = mResumedActivity;
...
// prev.app:ProcessRecord
// prev.app.thread:IApplicationThread
if (prev.app != null && prev.app.thread != null) {
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags, dontWait);
} else {
...
}
}
这里的prev.app.thread
是app
进程在系统进程的binder
代理,即ApplicationThreadProxy
,所以这里是第一次从系统进程切回到app
进程的binder
线程池当中,然后binder
的真正实现ApplicationThread
是在app
进程实现的,看下ApplicationThread
的schedulePauseActivity(...)
「运行在app
进程的binder
线程池里面」
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
sendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? 1 : 0) | (dontReport ? 2 : 0),
configChanges);
}
ActivityThread
的sendMessage(...)
private void sendMessage(int what, Object obj, int arg1, int arg2) {
sendMessage(what, obj, arg1, arg2, false);
}
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; //在这里what = PAUSE_ACTIVITY
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
可以看出,通过ActivityThread
自定义的Handler
发送了消息,这个自定义的Handler
为
// ActivityThread的内部类
private class H extends Handler {...}
// 在ActivityThread中的变量定义
final H mH = new H();
app进程Binder线程池 -> app进程主线程
H mH
获取的Looper
应该是主线程的Looper
,所以这里mH
是主线程的Handler
,这里通过Handler
的消息机制,将Activity
的启动从app
进程的Binder
线程池中切换到app
进程的主线程中
H
在handleMessage
处理如下
public void handleMessage(Message msg) {
switch (msg.what) {
...
case PAUSE_ACTIVITY:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
handlePauseActivity((IBinder)msg.obj, false, (msg.arg1&1) != 0, msg.arg2,(msg.arg1&2) != 0);
maybeSnapshot();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
...
}
}
调用了ActivityThread
的handlePauseActivity
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
...
performPauseActivity(token, finished, r.isPreHoneycomb());
...
}
ActivityThread
的performPauseActivity(...)
final Bundle performPauseActivity(IBinder token, boolean finished,
boolean saveState) {
ActivityClientRecord r = mActivities.get(token);
return r != null ? performPauseActivity(r, finished, saveState) : null;
}
// 调用到下面
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState) {
...
if (!r.activity.mFinished && saveState) {
// 最终会调用到Activity的onSaveInstanceState(Bundle outState)
callCallActivityOnSaveInstanceState(r);
}
...
// 最终会调用到Activity的onPause()
mInstrumentation.callActivityOnPause(r.activity);
...
}
callCallActivityOnSaveInstanceState(...)
最终会调用到Activity
的onSaveInstanceState(Bundle outState)
mInstrumentation.callActivityOnPause(...)
最终会调用到Activity
的onPause
Instrumentation
的callActivityOnPause(...)
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
Activity
的performPause(...)
final void performPause() {
...
onPause();
...
}
这里Activity
的生命周期方法onSaveInstanceState(Bundle outState)
和onPause(...)
由于前面的进程和线程切换,所以均是在app
进程的主线程进行的
- 调用
ActivityStackSupervisor
的startSpecificActivityLocked(xxx)
进程切换第三次:app进程 -> 系统进程Binder线程池
前面切换到app
进程时,系统进程的线程是挂起状态,等app
进程执行完上面所说的,就自动又回到系统进程,之后执行如下面
3.ActivityStackSupervisor
这里的调用又从ActivityStack
回到了ActivityStackSupervisor
,看ActivityStackSupervisor
的startSpecificActivityLocked(xxx)
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// 这是要启动的Activity的进程
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
r.task.stack.setLaunchTime(r);
// 如果要启动的Activity的进程已经存在
if (app != null && app.thread != null) {
try {
...
// 调用realStartActivityLocked(xxx)
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
} (--if结束)
// 如果进程不存在,则通过zygote创建应用进程
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
这里分析的是:在一个app
的已有的Activity
之上,启动另外一个Activity
,这两个Activity
属于同一个app
、同一个进程。所以它会走到if
里面,调用到realStartActivityLocked(xxx)
,而不会走到mService.startProcessLocked(xxx)
,那么什么情况下会走到这里呢?比如现在要在自己的app
启动淘宝app
的MainActivity
,那么淘宝app
所在的进程当然是不存在的,那么就不会走到if
里面,而是通过mService.startProcessLocked(xxx)
创建新的进程。
当然,这里分析的是:在一个app
的已有的Activity
之上,启动另外一个Activity
,这两个Activity
属于同一个app
、同一个进程。创建进程的那一条逻辑可以后面再看看。所以接下来就看看ActivityStackSupervisor
的realStartActivityLocked(xxx)
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),r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,results, newIntents,!andResume, mService.isNextTransitionForward(),profilerInfo);
......
}
这里的app
类型是ProcessRecord
,app.thread
的类型是IApplicationThread
,从前面的「笔记」 IBinder contextThread
那里可以得知,IApplicationThread
的真正实现是ApplicationThread
realStartActivityLocked(xxx)
的ProcessRecord app
参数,是在startSpecificActivityLocked(xxx)
的下面代码获取并传送到realStartActivityLocked(xxx)
方法里的
// 这是要启动的Activity的进程
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
app
它代表了要启动的Activity
的进程
进程切换第四次:系统进程 -> app进程Binder线程池
关键点:这个app
代表的是Activity
要启动的进程,这时候通过app.thread
获取的IApplicationThread
的真正实现应该是在启动Activity
的本地端实现的,更确切的说,这个app.thread
获取的应该是IApplicationThread
的代理类ApplicationThreadProxy
,其真正的实现类应该是在本地端实现的ApplicationThread
,也就是scheduleLaunchActivity(...)
方法应该是在本地端的Binder
线程池里面执行的。所以,从这里就将Activity
的启动又从系统进程切换到app
进程「也就是本地端」了
ApplicationThreadProxy
接上面的系统进程 -> app进程的Binder线程池
ApplicationThread
是ActivityThread
的内部类,看下它的scheduleLaunchActivity(xxx)
方法
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
IVoiceInteractor voiceInteractor, int procState, Bundle state,
PersistableBundle persistentState, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
ProfilerInfo profilerInfo) {
updateProcessState(procState, false);
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
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;
updatePendingConfiguration(curConfig);
sendMessage(H.LAUNCH_ACTIVITY, r);
}
这个方法主要是发送了一个启动Activity
的消息给Handler
处理
app进程的Binder线程池 -> app进程的主线程
private void sendMessage(int what, Object obj) {
sendMessage(what, obj, 0, 0, false);
}
//调用到这里
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
类型是 final H mH = new H();
H
继承至Handler
,是ActivityThread
的内部类,如下
private class H extends Handler {
public static final int LAUNCH_ACTIVITY = 100;
...
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的类型是LoadedApk
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
...
}
...
}
...
}
关键点:前面已经从系统进程切回到了app
进程的Binder
线程池中运行,然后这里的app
进程的ActivityThread
又代表着UI线程
,即主线程,ActivityThread
的自定义的Handler
定义为final H mH = new H()
,这里获取的Looper
应该就是主线程的Looper
,所以这个自定义Handler
应该是主线程的Handler
,也就是这里通过Handler
的消息机制,将Activity
的启动又从app
进程的Binder
线程池中切换到app
进程的主线程中,在app
进程的主线程中进行Activity
的启动,所以后面的生命周期方法onCreate
、onStart
、onResume
这些都是运行app
进程的主线程中
handleLaunchActivity
H
的handleMessage
在处理LAUNCH_ACTIVITY
这个消息的时候,调用了外部类ActivityThread
的handleLaunchActivity(xxx)
方法
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
// performLaunchActivity(xxx)方法最终完成了Activity对象的创建和启动过程
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
...
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed);
} else {
// If there was an error, for any reason, tell the activity
// manager to stop us.
try {
ActivityManagerNative.getDefault()
.finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
} catch (RemoteException ex) {
// Ignore
}
}
}
正常情况下,a != null
,会调用handleResumeActivity(xxx)
方法,来调用被启动的Activity
的onResume
的生命周期方法
performLaunchActivity
这个方法里,最终会调用到Activity
的onCreate(xxx)
、onStart(xxx)
、onRestoreInstanceState(xxx)
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// 1.获取待启动的Activity的组件信息
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
// 2.使用类加载器创建Activity对象
Activity activity = null;
try {
// 获取类加载器
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
// 通过类加载器来创建Activity对象
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
...
// 3.通过LoadedApk的makeApplication(xxx)方法来尝试创建Application对象
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
...
// 4.创建ContextImpl对象,并通过Activity的attach方法来完成一些重要数据的初始化
if (activity != null) {
// contextImpl对象
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "+ r.activityInfo.name + "with config " + config);
activity.attach(appContext, this, getInstrumentation(), r.token,r.ident, app, r.intent, r.activityInfo, title, r.parent,r.embeddedID, r.lastNonConfigurationInstances, config,r.voiceInteractor);
...
// 5.调用Activity的onCreate方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...
// 6.调用Activity的onStart方法
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
...
// 7.调用Activity的onRestoreInstanceState方法
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
...
}
...
}
ActivityThread
的performLaunchActivity
方法主要完成下面几件事情
- 从
ActivityClientRecord
中获取待启动的Activity
的组件信息
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
- 通过
Instrumentation
的newActivity
方法,使用类加载器创建Activity
对象
Activity activity = null;
try {
// 获取类加载器
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
// 通过类加载器来创建Activity对象
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
newActivity(xxx)
代码如下
// 通过类加载器来创建Activity对象
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
return (Activity)cl.loadClass(className).newInstance();
}
- 通过
LoadedApk
的makeApplication(xxx)
方法来尝试创建Application
对象
//ActivityThread.performLaunchActivity里
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
//r.packageInfo的类型是LoadedApk,其相应方法如下
public Application makeApplication(boolean forceDefaultAppClass,Instrumentation instrumentation) {
// 如果Application已经被创建过了,那么就不会再重复创建了,这意味着一个应用进程只有
// 一个Application对象
if (mApplication != null) {
return mApplication;
}
Application app = null;
...
java.lang.ClassLoader cl = getClassLoader();
...
// Application对象的创建也是通过Instrumentation来完成的,过程和Activity的创建一样,
// 都是通过类加载器来实现的
app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
...
mApplication = app;
if (instrumentation != null) {
try {
// 这里面会调用Application的onCreate()方法
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
...
}
}
...
return app;
}
- 创建
ContextImpl
对象,并通过Activity
的attach
方法来完成一些重要数据的初始化
// 这个activity对象,就是前面通过类加载器创建的对象
if (activity != null) {
// contextImpl对象
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "+ r.activityInfo.name + " with config " + config);
activity.attach(appContext, this, getInstrumentation(), r.token,r.ident, app, r.intent, r.activityInfo, title, r.parent,r.embeddedID, r.lastNonConfigurationInstances, config,r.voiceInteractor);
......
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
......
}
Activity
的attach
如下
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
// ContextImpl和Activity建立关联
attachBaseContext(context);
...
// 创建PhoneWindow对象
mWindow = PolicyManager.makeNewWindow(this);
// 设置回调接口
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);
if (info.softInputMode!=WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED){
mWindow.setSoftInputMode(info.softInputMode);
}
if (info.uiOptions != 0) {
mWindow.setUiOptions(info.uiOptions);
}
...
// 为PhoneWindow设置WindowManager
mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
if (mParent != null) {
mWindow.setContainer(mParent.getWindow());
}
// 获取WindowManager并赋值给Activity的成员变量mWindowManager,
// 这样在Activity就可以通过getWindowManager方法来获取WindowManager
mWindowManager = mWindow.getWindowManager();
mCurrentConfig = config;
}
在attach(xxx)
里,会建立ContextImpl
和Activity
的关联,还会完成Window
的创建并通过接口回调的方式建立Activity
和Window
的关联,这样当Window
接收到外部输入事件后就可以将事件传递给Activity
- 调用
Activity
的onCreate
在执行完attach
之后,performLaunchActivity
会调用下面的代码
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
在这里,最终会调用到Activity
的onCreate(Bundle savedInstanceState) {...}
- 调用
Activity
的onStart
之后,ActivityThread
的performLaunchActivity(xxx)
里面,还有下面的一段代码
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
Activity
的performStart(xxx)
final void performStart() {
...
mInstrumentation.callActivityOnStart(this);
...
}
Instrumentation
的callActivityOnStart(xxx)
public void callActivityOnStart(Activity activity) {
activity.onStart();
}
- 调用
Activity
的onRestoreInstanceState
之后,ActivityThread
的performLaunchActivity(xxx)
里面,还有下面的一段代码
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
Instrumentation
的callActivityOnRestoreInstanceState(xxx)
public void callActivityOnRestoreInstanceState(Activity activity, Bundle savedInstanceState) {
activity.performRestoreInstanceState(savedInstanceState);
}
Activity
的performRestoreInstanceState(xxx)
final void performRestoreInstanceState(Bundle savedInstanceState) {
onRestoreInstanceState(savedInstanceState);
restoreManagedDialogs(savedInstanceState);
}
可以看出,这里就调用了Activity
的onRestoreInstanceState(xxx)
handleResumeActivity
在这个方法里,会调用到Activity
的onResume(xxx)
handleLaunchActivity(xxx)
在调用了performLaunchActivity(xxx)
之后,会调用handleResumeActivity(xxx)
,在handleResumeActivity(xxx)
里面,最终会调用到Activity
的onResume(xxx)
和makeVisible(xxx)
,具体过程如下
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume) {
...
ActivityClientRecord r = performResumeActivity(token, clearHide);
...
r.activity.makeVisible();
...
}
performResumeActivity(xxx)
最终会调用到Activity
的onResume
makeVisible(xxx)
会完成Activity
的DecorView
的添加和显示的过程
performResumeActivity(xxx)
的具体调用过程如下
// ActivityThread
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide) {
...
r.activity.performResume();
...
}
// Activity
final void performResume() {
...
mInstrumentation.callActivityOnResume(this);
...
}
//Instrumentation
public void callActivityOnResume(Activity activity) {
activity.mResumed = true;
//调用到了Activity的onResume()
activity.onResume();
...
}
至此,就完成了整个Activity
的启动!
流程图
总结
IBinder总结
整个Activity
启动的IBinder
出现的两个Binder
:IApplicationThread
、IActivityManager
,这里再次对它们进行总结一下
IActivityManager
//Binder接口
public interface IActivityManager extends IInterface {...}
//Binder类,相当于Stub
public abstract class ActivityManagerNative extends Binder implements IActivityManager{.}
//Binder类的具体实现
public final class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {...}
//Binder类的本地代理,相当于Proxy,定义在ActivityManagerNative里面,不同进程下,通过 //ActivityManagerNative的asInterface,即可将AMS「继承至Stub」转化为ActivityManagerProxy //「Proxy」
class ActivityManagerProxy implements IActivityManager{...}
IActivityManager
定义的方法,只列出一部分
public interface IActivityManager extends IInterface {
public int startActivity(...) throws RemoteException;
public int startActivityAsUser(...) throws RemoteException;
public int startActivityAsCaller(...) throws RemoteException;
public WaitResult startActivityAndWait(...) throws RemoteException;
...
public boolean finishActivity(...) throws RemoteException;
public void finishSubActivity(...) throws RemoteException;
...
public void finishReceiver(...) throws RemoteException;
public void attachApplication(...) throws RemoteException;
public void activityResumed(...) throws RemoteException;
public void activityIdle(...) throws RemoteException;
public void activityPaused(...) throws RemoteException;
public void activityStopped(...) throws RemoteException;
...
public ComponentName startService(...) throws RemoteException;
public int stopService(...) throws RemoteException;
public boolean stopServiceToken(...) throws RemoteException;
public void setServiceForeground(...) throws RemoteException;
public int bindService(...) throws RemoteException;
public boolean unbindService(...) throws RemoteException;
...
}
IApplicationThread
//Binder接口
public interface IApplicationThread extends IInterface {...}
//Binder类,相当于Stub
public abstract class ApplicationThreadNative extends Binder implements IApplicationThread {}
//继承至Binder类,也就说这个相当于是Binder类的真正实现,相当于上面AMS的aidl逻辑分析中的Binder_1
private class ApplicationThread extends ApplicationThreadNative {...}
//代理对象如下,定义在ActivityThreadNative里面
class ApplicationThreadProxy implements IApplicationThread {...}
IApplicationThread
定义的方法,只列出一部分
public interface IApplicationThread extends IInterface {
void schedulePauseActivity(...) throws RemoteException;
void scheduleStopActivity(...) throws RemoteException;
void scheduleWindowVisibility(...) throws RemoteException;
void scheduleSleeping(...) throws RemoteException;
void scheduleResumeActivity(...) throws RemoteException;
void scheduleSendResult(...) throws RemoteException;
void scheduleLaunchActivity(...) throws RemoteException;
void scheduleRelaunchActivity(...) throws RemoteException;
void scheduleNewIntent(...) throws RemoteException;
void scheduleDestroyActivity(...) throws RemoteException;
void scheduleReceiver(...) throws RemoteException;
...
void dumpService(...) throws RemoteException;
void dumpProvider(...) throws RemoteException;
...
}
个人感觉:IActivityManager
应该是更偏向于app
进程向系统进程发出「启动活动、开启服务、绑定服务」这类请求,而IApplicationThread
则更偏向于系统进程跟app
进程说「Activity
要onPause
了,要调用什么什么生命周期方法了...」
流程总结
- 首先是在
app
进程,调用Activity
的startActivity(...)
,然后在Instrumentation
的execStartActivity(...)
会获取AMS
在app
进程的代理AMP
,调用AMP
的方法,就有了进程切换第一次:app进程 -> 系统进程的Binder线程池 - 调用
AMP
的方法,实际上是调用AMS
在系统进程的startActivity(...)
,之后调用会走到ActivityStackSupervisor
里,然后再走到ActivityStack
,在ActivityStack
的startPausingLocked(...)
里,会拿到app
进程在系统进程的binder
代理ApplicationThreadProxy
,调用它的schedulePauseActivity(...)
,真正的实现是在app
进程的ApplicationThread
,就有了进程切换第二次:系统进程 -> app进程Binder线程池 - 之后通过
Handler
,进行线程切换,为app进程Binder线程池 -> app进程主线程,在app
进程主线程执行上一个Activity
的onSaveInstanceState(Bundle outState)、onPause()
生命周期方法调用(onStop()
的调用不知道在哪,这篇文章就不分析了),也就是当前正在显示的Activity
进行onPause
操作,然后要启动的Activity
才能进行onResume
操作 - 等上一个
Activity
的onPause
那些生命周期方法执行完,就又自动切换到系统进程,也就是进程切换第三次:app进程 -> 系统进程Binder线程池 - 之后调用又走到了
ActivityStackSupervisor
,然后在ActivityStackSupervisor
的realStartActivityLocked(...)
里,仍然是拿到app
进程在系统进程的binder
代理,即ApplicationThreadProxy
,真正的实现是在app
进程的ApplicationThread
,调用它的scheduleLaunchActivity(...)
,就有了进程切换第四次:系统进程 -> app进程Binder线程池 - 然后通过
Handler
进行线程切换,为app进程Binder线程池 -> app进程主线程,然后在app
进程的主线程创建Activity
对象,尝试创建Application
对象,调用Activity
的attach(...)
方法,在attach(...)
里会创建PhoneWindow
对象,为PhoneWindow
设置Activity
的回调接口,调用Activity
的onCreate(...)
,如果在onCreate(...)
里进行setContentView(...)
,那么就会完成Activity
的DecorView
的创建和初始化,然后调用Activity
的onStart()、onRestoreInstanceState()、onResume()
,然后调用Activity
的makeVisible(...)
,在makeVisible(...)
里,会将Activity
的DecorView
通过WindowManager
的addView(...)
(进行View
的绘制等)正式添加到Window
当中,这时候,DecorView
才真正的完成了添加和显示的这两个过程,到这里Activity
的视图才能被用户看到。
参考
《Android 开发艺术探索》