赞
踩
Activity的启动流程分两种
- 一是从桌面点击图标,启动MainActivity
- 二是从程序内调用StartActivity 启动Activity
- 二者区别就在于
- 第一种要启动进程在启动MainActivity
- 第二种是直接启动Activity
这里说下第二种 区别于第一种 就是省略了一个启动应用进程的步骤
- 如果不了解Activity栈管理相关类 可以参看Activity栈管理类
## 步骤总结
调用StartActivity获取AMS的Binder代理对象,该对象利用Binder驱动通知AMS要启动一个Activity的消息.
(AMS管理启动Activity)AMS接收到消息之后,开始管理启动MainActivity的工作,并通过Binder驱动通知给Launcher自己要创建Activity,需要launcer进入Paused状态,当Launcher进入paused状态之后,就开始启动Activity
启动Activity,判断当前的Activity所属的应用进程是否存在
若存在,则执行realStartActivityLocked
方法去启动准备好的Activity
AMS利用binder通知ActivityThread来启动Activity
调用
StartActivity
,最终会执行到startActivityForResult
startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { ···· Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); ··· } } public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; ................ int result = ActivityManager.getService() .startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); .................. return null; }
mInstrumentation
是Activity类的成员变量,它的类型是Intrumentation
,它用来监控应用程序和系统的交互。mMainThread.getApplicationThread()
来获取它里面的ApplicationThread成员变量,它是一个Binder对象,后面ActivityManagerService会使用它来和ActivityThread来进行进程间通信。通过
ActivityManager.getService()
获取AMS的代理对象
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
//利用单例获取,通过Binder驱动获取amd的dialing对象
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;
}
};
ActivityManager.getService()
返回ActivityManagerService的代理对象
StartActivity
了在
execStartActivity
方法中,AMs的代理对象调用了start方法,通过Binder驱动就会执行AMS中的StartActivity
ActivityManager.getService().startActivity
-》AMS.StartActivity()
AMS源码位置
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@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());
}
AMS源码位置
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
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) {
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null,
"startActivityAsUser");
}
ActivityStarter#startActivityMayWait
ActivityStarter
源码位置frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
ActivityStarter#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 globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId, IActivityContainer iContainer, TaskRecord inTask, String reason) { .................. boolean componentSpecified = intent.getComponent() != null; .................. intent = new Intent(intent); ......................省略intent赋值部分 ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId); ..................... // 1 根据intent去收集需要启动的activity的信息,包名和要启动的MainActivity ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo); ActivityOptions options = ActivityOptions.fromBundle(bOptions); ActivityStackSupervisor.ActivityContainer container = (ActivityStackSupervisor.ActivityContainer)iContainer; .................. synchronized (mService) { final ActivityStack stack; if (container == null || container.mStack.isOnHomeDisplay()) { stack = mSupervisor.mFocusedStack; } else { stack = container.mStack; } ................................ final ActivityRecord[] outRecord = new ActivityRecord[1]; // 2 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); return res; } }
startActivityLocked
进一步操作通知launcher要启动Activity请进入paused
startActivityLocked
进一步操作
ActivityStarter#startActivityLocked
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) { ................. 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); ................... return mLastStartActivityResult; }
startActivity
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) { int err = ActivityManager.START_SUCCESS; // Pull the optional Ephemeral Installer-only bundle out of the options early. final Bundle verificationBundle = options != null ? options.popAppVerificationBundle() : null; //从传进来的参数caller得到调用者的进程信息,并保存在callerApp变量中, //这里就是Launcher应用程序的进程信息了。 ProcessRecord callerApp = null; if (caller != null) { callerApp = mService.getRecordForAppLocked(caller); if (callerApp != null) { callingPid = callerApp.pid; callingUid = callerApp.info.uid; } else { ................ } } ................................ //保存launcher的binder对象 //参数resultTo是Launcher这个Activity里面的一个Binder对象 //通过它可以获得Launcher这个Activity的相关信息,保存在sourceRecord变量中。 ActivityRecord sourceRecord = null; ActivityRecord resultRecord = null; if (resultTo != null) { sourceRecord = mSupervisor.isInAnyStackLocked(resultTo); if (DEBUG_RESULTS) Slog.v(TAG_RESULTS, "Will send result to " + resultTo + " " + sourceRecord); if (sourceRecord != null) { if (requestCode >= && !sourceRecord.finishing) { resultRecord = sourceRecord; } } } ............. //创建即将要启动的Activity的相关信息,并保存在r变量中 ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null, mSupervisor, container, options, sourceRecord); return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true, options, inTask, outActivity); }
startActivity
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
int result = START_CANCELED;
try {
mService.mWindowManager.deferSurfaceLayout();
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, doResume,
options, inTask, outActivity);
} finally {
............
}
..................
return result;
}
startActivityUnchecked
ActivityStarter#startActivityUnchecked
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, ActivityRecord[] outActivity) { // 初始化ActivityStarter全局变量 setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,voiceInteractor); // 检测Activity是否启动模式,是否需要在新的栈中启动,对与新的进程、SingleTask、SingleInstance启动模式就需要在新的栈中启动, 一般是判断是否需要在mLaunchFlags中加入FLAG_ACTIVITY_NEW_TASK computeLaunchingTaskFlags(); //检测当前栈 computeSourceStack(); //最终确定Task启动方式 mIntent.setFlags(mLaunchFlags); // 判断是否应将新Activity插入到现有任务栈中 // 如果不需要,则返回null,如果需要,则返回该任务栈信息 ActivityRecord reusedActivity = getReusableIntentActivity(); //判断是否可以重新利用 if (reusedActivity != null) { ............... if (reusedActivity.getTask().intent == null) { //如果历史记录中有匹配的任务,找出应该将哪个放到前面 reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity); //设置为当前栈顶或最先创建的活动 setTaskFromIntentActivity(reusedActivity); } //恢复当前focus的堆栈stack中的顶端活动对象top activity mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity, mOptions); return START_SUCCESS; }
ActivityStackSupervisor#resumeFocusedStackTopActivityLocked
源码位置
frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
boolean resumeFocusedStackTopActivityLocked(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) { //如果目标栈不为空且是焦点栈,则直接将准备的activityRecord设置为栈顶活动 if (targetStack != null && isFocusedStack(targetStack)) { return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); } //获取能运行的栈中的栈顶ActivityRecord final ActivityRecord r = mFocusedStack.topRunningActivityLocked(); if (r == null || r.state != RESUMED) { mFocusedStack.resumeTopActivityUncheckedLocked(null, null); } else if (r.state == RESUMED) { // Kick off any lingering app transitions form the MoveTaskToFront operation. mFocusedStack.executeAppTransition(targetOptions); } return false; }
ActivityStack#resumeTopActivityUncheckedLocked
ActivityStack源码路径
frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
boolean result = false;
//设置栈顶Activity
result = resumeTopActivityInnerLocked(prev, options);
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//暂停失去焦点的活动对象 如果是启动Launcher进程 这里不会做操作因为launcher之前没有activity
boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
//准备暂定活动这里准备暂停的是Launcher
pausing |= startPausingLocked(userLeaving, false, next, false);
}
// 启动Activity
mStackSupervisor.startSpecificActivityLocked(next, true, true);
return true;
}
启动准备好的Activity
ActivityStackSupervisor.startSpecificActivityLocked
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) { // Is this activity's application already running? 此活动的应用程序是否已在运行? //1 获取即将启动的Activiy所在的应用程序进程 ProcessRecord app = mService.getProcessRecordLocked(r.processName, r.info.applicationInfo.uid, true); r.getStack().setLaunchTime(r); //2 判断是否运行 运行 则执行 realStartActivityLocked if (app != null && app.thread != null) { try { if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0 || !"android".equals(r.info.packageName)) { app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode, mService.mProcessStats); } //3 启动Activity realStartActivityLocked(r, app, andResume, checkConfig); return; } catch (RemoteException e) { } } //4 若没运行则 创建新的进程 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false, true); }
获取即将启动的Activiy所在的应用程序进程
若存在启动Activity
这里是在应用内启动,所以上面应用程序进程是存在的
执行ActivityStackSupervisor#realStartActivityLocked
不存在则创建进程,这里启动的是MainActivity 肯定是不存在的
#### 4.1 AMS 通知给ActivityThread
realStartActivityLocked
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
................
//在这里AMS通过ApplicationThread的binder对象,通过Binder驱动, 执行到了ActivityThread里的scheduleLaunchActivity
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);
}
ActivityThread#scheduleLaunchActivity
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(); // 发送一个LAUNCH_ACTIVITY 并将活动传递 sendMessage(H.LAUNCH_ACTIVITY, r); }
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
//调用HandleLauncheActivity启动
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
} break;
}
handleLaunchActivity
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) { // 创建Activity对象 Activity a = performLaunchActivity(r, customIntent); if (a != null) { //通知对象可见 handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason); } else { //创建失败则关闭该activity try { ActivityManager.getService() .finishActivity(r.token, Activity.RESULT_CANCELED, null, Activity.DONT_FINISH_TASK_WITH_ACTIVITY); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } }
performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")"); //收集Activity相关信息,包信息,组件信息 ComponentName component = r.intent.getComponent(); if (component == null) { component = r.intent.resolveActivity( mInitialApplication.getPackageManager()); r.intent.setComponent(component); } //创建上下文 ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null; try { //通过类加载机制将Activity加载进来 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); } } catch (Exception e) { .... } ..................... //声明Window对象 Window window = null; try { //创建Application对象 当前进程内全局唯一 Application app = r.packageInfo.makeApplication(false, mInstrumentation); if (activity != null) { //attach内部首先调用了attachBaseContex绑定上下文信息, //创建PhoneWindow并给其设置Windowmanager处理 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); //通过mInstrumentation执行Activity的onCreate方法 if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } ............. } } catch (SuperNotCalledException e) { ................. } return activity; }
通过类加载机制加载activity
通过调用Activity#attach 绑定上下文信息,创建PhoneWindow给Windowmanager处理
并通过Instrumentation的callActivityOnCreate方法来执行Activity的OnCreate
在oncreate中执行setContentView创建布局 在ActivityResume时 将布局添加到window
callActivityOnCreate
public void callActivityOnCreate(Activity activity, Bundle icicle, PersistableBundle persistentState) { prePerformCreate(activity); activity.performCreate(icicle, persistentState); postPerformCreate(activity); }
- 1
- 2
- 3
- 4
- 5
- 6
- 内部通过
Activity#performCreate
执行Activity的onCreatefinal void performCreate(Bundle icicle) { restoreHasCurrentPermissionRequest(icicle); // 最后回调OnCrate方法 onCreate(icicle); mActivityTransitionState.readState(icicle); performCreateCommon(); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
在这里涉及到显示布局,也是就是Activtiy绘制这里仅点出 并不分析
在4.2.3.1中可知创建的Activity不为空.所以4.2.3后面执行了handleLaunchActivity
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) { ActivityClientRecord r = mActivities.get(token); if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) { return; } r = performResumeActivity(token, clearHide, reason); //..................... if (r != null) { final Activity a = r.activity; //......... //显示onCreate setContentView 创建的布局 通过wm.addview if (r.window == null && !a.mFinished && willBeVisible) { r.window = r.activity.getWindow(); View decor = r.window.getDecorView(); decor.setVisibility(View.INVISIBLE); ViewManager wm = a.getWindowManager(); WindowManager.LayoutParams l = r.window.getAttributes(); a.mDecor = decor; l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION; l.softInputMode |= forwardBit; //........ if (a.mVisibleFromClient) { if (!a.mWindowAdded) { a.mWindowAdded = true; wm.addView(decor, l); } } //........... } //通知AMS 该activity 已经可见并了 if (reallyResume) { try { ActivityManager.getService().activityResumed(token); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } } }
在这里涉及到显示布局,也是就是Activtiy绘制这里仅点出 并不分析
在4.2.3.1中可知创建的Activity不为空.所以4.2.3后面执行了handleResumeActivity
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) { ActivityClientRecord r = mActivities.get(token); if (!checkAndUpdateLifecycleSeq(seq, r, "resumeActivity")) { return; } r = performResumeActivity(token, clearHide, reason); //..................... if (r != null) { final Activity a = r.activity; //......... //显示onCreate setContentView 创建的布局 通过wm.addview if (r.window == null && !a.mFinished && willBeVisible) { r.window = r.activity.getWindow(); View decor = r.window.getDecorView(); decor.setVisibility(View.INVISIBLE); ViewManager wm = a.getWindowManager(); WindowManager.LayoutParams l = r.window.getAttributes(); a.mDecor = decor; l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION; l.softInputMode |= forwardBit; //........ if (a.mVisibleFromClient) { if (!a.mWindowAdded) { a.mWindowAdded = true; wm.addView(decor, l); } } //........... } //通知AMS 该activity 已经可见并了 if (reallyResume) { try { ActivityManager.getService().activityResumed(token); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } } }
至此Activity启动结束。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。