一、Activity工作流程的前半部分
(1)Activity.startActivity()源码
- 步骤一:mMainThread是一个ActivityThread对象,初始化在当前Activity的attach方法中;mMainThread.getApplicationThread()返回的是一个ApplicationThread对象,ApplicationThread是ActivityThread的内部类。
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
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);
}
}
}
(2)ApplicationThread源码
- ApplicationThread继承了IApplicationThread.Stub,说明这里Android使用了AIDL技术实现进程间通信。因此,ApplicationThread就是一个Binder对象,它重写了IApplicationThread接口的抽象方法,这些重写的方法一定会在某一刻,基于Binder机制被调用。
public final class ActivityThread extends ClientTransactionHandler {
//code...
final ApplicationThread mAppThread = new ApplicationThread();
//code...
private class ApplicationThread extends IApplicationThread.Stub {
//code...
}
//code...
}
(3)Instrumentation.execStartActivity源码
- 步骤一:基于Binder机制,通过调用代理对象IActivityManager的方法,使得系统服务ActivityManagerService对应的方法被调用。因此,启动Activity的操作就交给了系统服务ActivityManagerService来处理了。
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
//code...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
//步骤一
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target, requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
(4)ActivityManager.getService源码
- 步骤一:ActivityManager.getService()方法返回代理对象IActivityManager。
- 步骤二:获取一个关联系统服务ActivityManagerService的Binder对象。
- 步骤三:返回一个IActivityManager的代理对象
//步骤一
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
//步骤二
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
//步骤三
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
(5)Singleton源码
- Singleton是一个抽象类,有一个抽象方法create()。有一个get()方法,内部通过单例模式创建T对象,调用create方法创建T对象,且只会创建一次T对象。
public abstract class Singleton<T> {
private T mInstance;
protected abstract T create();
public final T get() {
synchronized (this) {
if (mInstance == null) {
mInstance = create();
}
return mInstance;
}
}
}
二、启动Activity的操作交给ActivityManagerService处理
(1)ActivityManagerService.startActivity源码
public class ActivityManagerService extends IActivityManager.Stub implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
//code...
@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());
}
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = mUserController.handleIncomingUser(Binder.getCallingPid(),
Binder.getCallingUid(), userId, false, ALLOW_FULL_ONLY, "startActivity", null);
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo,
null, null, bOptions, false, userId, null, null, "startActivityAsUser");
}
//code...
}
(2)ActivityStarter源码
- 变量mSupervisor是一个ActivityStackSupervisor对象。
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 globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,IActivityContainer iContainer, TaskRecord inTask, String reason) {
//code...
int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,aInfo, rInfo, voiceSession, voiceInteractor,resultTo, resultWho, requestCode, callingPid,callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, outRecord, container,inTask, reason);
//code...
}
int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,String callingPackage, int realCallingPid, int realCallingUid, int startFlags,ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,TaskRecord inTask, String reason) {
//code...
mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,container, inTask);
//code...
}
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,String callingPackage, int realCallingPid, int realCallingUid, int startFlags,ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,TaskRecord inTask) {
//code...
doPendingActivityLaunchesLocked(false);
//code...
}
final void doPendingActivityLaunchesLocked(boolean doResume) {
//code...
startActivity(pal.r, pal.sourceRecord, null, null, pal.startFlags, resume, null,null, null /*outRecords*/);
//code...
}
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {
//code...
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, doResume, options, inTask, outActivity);
//code...
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {
//code...
mSupervisor.resumeFocusedStackTopActivityLocked();
//code...
}
(3)查看ActivityStackSupervisor源码
- mFocusedStack是一个ActivityStack对象;
boolean resumeFocusedStackTopActivityLocked() {
return resumeFocusedStackTopActivityLocked(null, null, null);
}
boolean resumeFocusedStackTopActivityLocked(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
//code...
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
//code...
}
(4)ActivityStack源码
- mSupervisor是一个ActivityStackSupervisor对象;
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mStackSupervisor.inResumeTopActivity) {
//code...
result = resumeTopActivityInnerLocked(prev, options);
//code...
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//code...
mStackSupervisor.startSpecificActivityLocked(next, true, true);
//code...
}
(5)查看ActivityStackSupervisor源码
- 变量app是一个ProcessRecord对象,它的成员变量thread是IApplicationThread类型,因此app.thread是一个IApplicationThread的代理对象。
- app.thread调用scheduleLaunchActivity方法,通过Binder机制,会使ApplicationThread.scheduleLaunchActivity()方法被调用。于是,基于Binder机制,实现了一次进程间的通信,将启动Activity的操作交给了ApplicationThread类。
void startSpecificActivityLocked(ActivityRecord r,boolean andResume, boolean checkConfig) {
//code...
realStartActivityLocked(r, app, andResume, checkConfig);
//code...
}
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,boolean andResume, boolean checkConfig) throws RemoteException {
//code...
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,System.identityHashCode(r), r.info,mergedConfiguration.getGlobalConfiguration(),mergedConfiguration.getOverrideConfiguration(), r.compat,r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,r.persistentState, results, newIntents, !andResume,mService.isNextTransitionForward(), profilerInfo);
//code...
}
三、启动Activity的操作,交给ApplicationThread来处理
(1)ApplicationThread.scheduleLaunchActivity源码
- 步骤一:创建了一个ActivityClientRecord对象,用于封装启动Activity需要的一些参数值。
- 步骤二:调用ActivityThread.sendMessage方法发送消息
@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);
}
(2)ActivityThread.sendMessage源码
- 步骤一:mH是一个H对象,类H是ActivityThread的内部类,并继承了Handler。于是,启动Activity的操作放在处理消息的方法handleMessage中。
//最终调用
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
//步骤一
mH.sendMessage(msg);
}
(3)handleMessage源码
- 步骤一:调用ActivityThread.getPackageInfoNoCheck方法,返回一个LoadedApk对象,并将该对象封装到ActivityClientRecord的packgeInfo字段中。
- 步骤二:调用ActivityThread.handleLaunchActivity方法启动Activity;
class H extends Handler {
public void handleMessage(Message msg) {
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;
//code...
}
(4)handleLaunchActivity源码
- 步骤一:调用performLaunchActivity方法启动Activity
@Override
public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) {
//code...
//步骤一
final Activity a = performLaunchActivity(r, customIntent);
//code...
return a;
}
(5)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);
}
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);
}
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
//code...
java.lang.ClassLoader cl = appContext.getClassLoader();
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);
}
//code...
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
//code...
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, r.configCallback);
//code...
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
//code...
}
return activity;
}
ActivityThread中performLaunchActivity方法的操作:
- 获取要启动的Activity的ComponentName对象:里面包含了包名,类名相关的信息;
- 创建Activity的上下文环境:即创建了ContextImpl对象;
- 创建Activity的实例:调用Instrumentation中newActivity方法,并使用类加载器创建Activity对象;
- 创建Application对象;
- 调用Activity中attach方法:初始化Activity类里的一些数据;
- 启动Activity:调用Instrumentation.callActivityOnCreate方法;
二、总结
- startActivity调用startActivityForResult方法内部调用execStartActivity方法,execStartActivity方法内部调用ActivityManager.getService().startActivity()方法。基于Binder机制,通过调用代理对象IActivityManager的方法,使得系统服务ActivityManagerService对应的方法被调用。
- ActivityManagerService中startActivity方法通过层层方法调用到realStartActivityLocked方法,realStartActivityLocked内部调用app.thread.scheduleLaunchActivity()方法,通过Binder机制使ApplicationThread的scheduleLaunchActivity方法被调用,将启动Activity交由ActivityThread来处理。
- ApplicationThread.scheduleLaunchActivity方法封装Activity启动参数,通过sendMessage启动Activity,H是ActivityThread的内部类,并继承了Handler,启动Activity的操作放在处理消息的方法handleMessage中。调用ActivityThread中handleLaunchActivity方法,内部调用performLaunchActivity方法启动Activity。
- 调用performCreate方法,执行onCreate方法。
网友评论