Activity启动过程笔记

时间:2021-10-12 04:33:12

一、Activity启动方法解析:

由FirstActivity启动SecondActivity
Intent intent = new Intent(this,SecondActivity.class);
startActivity(intent);
Log:
Activity启动过程笔记
(1)FirstActivity调用onPause方法(2)SecondActivity调用onCreate、onStart、onResume方法,实现SecondActivity的准备工作,进入可交互的状态。(3)FirstActivity调用onStop进入FirstActivity的不可见状态。

二、开始启动Activity

Activity.startActivity() Activity.startActivityForResult Instrumentation.execStartActivty 
ActivityManagerNative.getDefault().startActivity
1、startActivity和startActivityForResult 最终调用的都是Activity的startActivityForResult()方法#Activity  
private Instrumentation mInstrumentation;

public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
if (mParent == null) {
//mMainThread.getApplicationThread()返回ApplicationThread,是ActivityThread的内部类。
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;
}

final View decor = mWindow != null ? mWindow.peekDecorView() : null;
if (decor != null) {
decor.cancelPendingInputEvents();
}
// TODO Consider clearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
2、调用Instrumentation的execStartActivity()Instrumentation是android系统中启动Activity的一个实际操作类
#Instrumentation 
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
if (am.match(who, null, intent)) {
am.mHits++;
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess();
//主要调用的方法
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, null, options);
checkStartActivityResult(result, intent); //检查Activity启动的结果
} catch (RemoteException e) {
}
return null;
}
总结:
(1)ActivityManagerNative.getDefault()
public abstract class ActivityManagerNative extends Binder implements IActivityManager
static public IActivityManager getDefault() {return gDefault.get();//Singleton是单例封装类,get方法最终调用的是create()}
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;}};
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);}
class ActivityManagerProxy implements IActivityManager{}
这里是应用进程向SystemServer进程进行消息传递的过程。ActivityManagerService属于SystemServer进程,与应用进程进行通信需要借助Binder机制。ActivityManagerNative与ActivityManagerProxy相当于一个Binder的客户端,而ActivityManagerService相当于Binder的服务端。ActivityManagerNative调用接口方法就会传递给ActivityManagerService,并调用其方法。
所以ActivityManagerNative.getDefault() 最终调用的是 ActivityManagerService的startActivity方法

三、ActivityManagerService的方法调用和ActivityStackSuperVisor、ActivityStack之间的方法传递。

ActivityManagerService.startActivity
ActivityManagerService.startActivityAsUser
ActivityStackSupervisor.startActivityMayWait
ActivityStackSupervisor.startActivityLocked
ActivityStackSupervisor.startActivityUncheckedLocked
ActivityStack.startActivityLocked
ActivityStackSupervisor.resumeTopActivitiesLocked
ActivityStack.resumeTopActivityLocked
ActivityStack.resumeTopActivityInnerLocked

1、ActivityManagerService方法调用#ActivityManagerService
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

ActivityStackSupervisor mStackSupervisor;

@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());
}

@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);
// TODO: Switch to user app stacks here.
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, options, userId, null, null);
}

}
2、ActivityStackSuperVisor、ActivityStack之间的方法传递(1)#ActivityStackSupervisor:调用startActivityMayWait方法,又调用了startActivityLocked方法,然后调用了startActivityUncheckedLocked方法。
final int startActivityUncheckedLocked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
boolean doResume, Bundle options, TaskRecord inTask) {
//调用了ActivityStack的startActivityLocked方法
targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
if (!launchTaskBehind) {
// Don't set focus on an activity that's going to the back.
mService.setFocusedActivityLocked(r, "startedActivity");
}
return ActivityManager.START_SUCCESS;
}
(2)#ActivityStack:
final void startActivityLocked(ActivityRecord r, boolean newTask,
boolean doResume, boolean keepCurTransition, Bundle options) {
...
if (doResume) {
mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
}
}
(3)#ActivityStackSupervisor:又调用了ActivityStackSupervisor的resumeTopActivitiesLocked方法
boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
Bundle targetOptions) {
if (targetStack == null) {
targetStack = mFocusedStack;
}
// Do targetStack first.
boolean result = false;
if (isFrontStack(targetStack)) {
result = targetStack.resumeTopActivityLocked(target, targetOptions);
}
.....
}
(4)#ActivityStack又调用了ActivityStack的resumeTopActivityLocked方法然后调用ActivityStack的resumeTopActivityInnerLocked方法
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
......
//一直执行到onPause方法
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
}
......
//继续执行启动Activity的过程
mStackSupervisor.startSpecificActivityLocked(next, true, false);

}

四、执行FirstActivity的onPause方法

ActivityStack.startPausingLocked() IApplicationThread.schudulePauseActivity() ApplicationThread.schedulePauseActivity
ActivityThread.handlePauseActivity
ActivityThread.performPauseActivity
Instrumentation.callActivityonPause
Activity.performPause
Activity.onPause

1、ActivityStack.startPausingLocked方法
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,
boolean dontWait) {
...
if (prev.app != null && prev.app.thread != null) {
if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
try {
EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
prev.userId, System.identityHashCode(prev),
prev.shortComponentName);
mService.updateUsageStats(prev, false);
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags, dontWait);
} catch (Exception e) {
// Ignore exception, if process died other code will cleanup.
Slog.w(TAG, "Exception thrown during pause", e);
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
} else {
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
...
}
注:这个过程是System进程与应用进程通讯的一个过程。其中prev.app.thread是一个IApplicationThread类型的对象,而在ActivityThread中也定义了一个ApplicationThread的类,其继承了IApplicationThread,并且都是Binder对象。IAppcation是一个Binder的client端而ActivityThread中的ApplicationThread是一个Binder对象的server端,所以通过这里的thread.schedulePauseActivity实际上调用的就是ApplicationThread的schedulePauseActivity方法。2、#ApplicationThread
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);
}
通过handler的消息传递,调用了ActivityThread的handlePauseActivity方法3、#ActivityThread
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
.....
performPauseActivity(token, finished, r.isPreHoneycomb());
.....
}
调用了ActivityThread的performPauseActivity的方法
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState) {
.....
mInstrumentation.callActivityOnPause(r.activity);
.....
}
调用了Instrumentation的callActivityonPause方法4、#Instrumentation
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
调用了Activity的performPause方法5、#Activity
final void performPause() {
mDoReportFullyDrawn = false;
mFragments.dispatchPause();
mCalled = false;
onPause();
mResumed = false;
if (!mCalled && getApplicationInfo().targetSdkVersion
>= android.os.Build.VERSION_CODES.GINGERBREAD) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onPause()");
}
mResumed = false;
}
最终调用了onPause方法

五、执行onCreate、onStart、onCreate方法

ActivityStackSupervisor.startSpecificActivityLocked()
ActivityStackSupervisor.realStartActivityLocked()
IApplicationThread.scheduleLaunchActivity
ApplicationThread.scheduleLaunchActivity
ActivityThread.handleLaunchActivity
ActivityThread.performLaunchActivity
Instrumentation.callActivityOnCreate
Activity.performCreate
Activity.onCreate


1、onCreate方法调用在ActivityStack的resumeTopActivityInnerLocked方法中,调用到了ActivityStackSupervisor的startSpecificActivityLocked方法。#ActivityStackSupervisor startSpecificActivityLocked
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
.....
//继续启动Activity
realStartActivityLocked(r, app, andResume, checkConfig);
return;
.....
//用于启动应用进程 ActivityThread
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
接着调用ActivityStackSupervisor的realStartActivityLocked。#ActivityStackSupervisor  realStartActivityLocked
final boolean realStartActivityLocked(ActivityRecord r,
ProcessRecord app, boolean andResume, boolean checkConfig)
throws RemoteException {

......
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,
results, newIntents, !andResume, mService.isNextTransitionForward(),
profilerInfo);

......
}
app.thead类型是IApplicationThread。IApplicationThread是一个Binder接口,继承了IInterface。里面包含了启动和停止Activity的接口,还包含了启动和停止服务的接口。
public final class ActivityThread {
private class ApplicationThread extends ApplicationThreadNative {

}
}
public abstract class ApplicationThreadNative extends Binder
implements IApplicationThread {}
ActivityThread内部类ApplicationThread继承于Binder实现了IApplicationThread接口。通过AppicationThread <– IApplicationThread实现了SystemServer进程与应用进程的通讯。通过ApplicationThread的scheduleLaunchActivity来启动Activity#ActivityThread.ApplicationThread 
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);
}
通过Handler处理,Activity的启动最终由ActivityThread的handleLaunchActivity方法实现。#ActivityThread:
private void handleLaunchActivity(ActivityClientRecord r,Intent customIntent){
.....
Activity a=performLaunchActivity(r,customIntent);

if(a!=null){
r.createdConfig=new Configuration(mConfiguration);
Bundle oldState=r.state;
handleResumeActivity(r.token,false,r.isForward,
!r.activity.mFinished&&!r.startsNotResumed);
}
.....
}
通过调用performLaunchActivity最终完成对activity的创建和启动的过程。
#ActivityThread:
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//(1)通过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);
}
//(2)通过Instrumentation的newActivity方法,使用类加载器创建activity对象。
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.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) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
//(3)通过LoaderApk的makeApplication方法 创建Application对象。
//Application也是通过Instrumentation创建,并且只能有一个Application对象
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);

if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
if (localLOGV) Slog.v(
TAG, r + ": app=" + app
+ ", appName=" + app.getPackageName()
+ ", pkg=" + r.packageInfo.getPackageName()
+ ", comp=" + r.intent.getComponent().toShortString()
+ ", dir=" + r.packageInfo.getAppDir());
//(4)创建ContextImpl对象并通过Activity的attach方法完成数据的初始化。
//在attach方法中完成Window的创建,并建立activity和window 的关联
if (activity != null) {
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 (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
//(5)调用Instrumentation的callActivityOnCreate方法
// 最终调用activity的onCreate方法完成Activity的启动。
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onCreate()");
}
r.activity = activity;
r.stopped = true;
if (!r.activity.mFinished) {
//(6)准备调用Activity的onStart方法
activity.performStart();
r.stopped = false;
}

}

return activity;
}
#Instrumentation
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
#Activity
final void performCreate(Bundle icicle) {
onCreate(icicle); //调用了onCreate方法
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mFragments.dispatchActivityCreated();
}
调用activity的onCreate方法

2、调用onStart方法:
ActivityThread.performLaunchActivity
Activity.performStart
Instrumentation.callActivityOnStart
Activity.onStart


在ActivityThread的performLaunchActivity中调用Activity的performStart方法#ActivityThread
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
.....
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
.....

return activity;
}
#Activity
final void performStart() {
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
mFragments.noteStateNotSaved();
mCalled = false;
mFragments.execPendingActions();
mInstrumentation.callActivityOnStart(this);
if (!mCalled) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onStart()");
}
mFragments.dispatchStart();
mFragments.reportLoaderStart();
mActivityTransitionState.enterReady(this);
}
调用到了Instrumentation的callActivityOnStart方法#Instrumentation
public void callActivityOnStart(Activity activity) {
activity.onStart();
}
调用了Activity的onStart方法

3、调用onResume方法
ActivityThread.handleLaunchActivity
ActivityThread.handleResumeActivity
ActivityThread.performResumeActivity
Activity.performResume
Instrumentation.callActivityOnResume
Activity.onResume


在ActivityThread的handleLaunchActivity方法中#ActivityThread
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
....
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed);

.....
}
调用了ActivityThread的handleResumeActivity方法
#ActivityThread
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume) {
.....
ActivityClientRecord r = performResumeActivity(token, clearHide);
.....
}
调用了performResumeActivity方法
#ActivityThread
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide) {
.....
r.activity.performResume();
.....
return r;
}
调用了Activity得performResume方法#Activity
final void performResume() {
....
mInstrumentation.callActivityOnResume(this);
.....
}
调用了Instrumentation的callActivityOnResume方法
#Instrumentation
public void callActivityOnResume(Activity activity) {
activity.mResumed = true;
activity.onResume();

if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
am.match(activity, activity, activity.getIntent());
}
}
}
}
调用了Activity的onResume方法

五、FirstActivity调用onStop方法

ActivityThread.handleResumeActivity()
Idler.queueIdle()
ActivityManagerNative.getDefault().activityIdle
ActivityManagerService.activityIdle
ActivityStackSupervisor.activityIdleInternalLocked
ActivityStack.stopActivityLocked
IApplicationThread.scheduleStopActivity
ApplicationThread.scheduleStopActivity
ActivityThread.handleStopActivity
ActivityThread.performStopActivityInner
Activity.performStop
Instrumentation.callActivityOnStop
Activity.onStop
1、在ActivityThread的handleResumeActivity方法中#ActivityThread handeResumeActivity
Looper.myQueue().addIdleHandler(new Idler());
#ActivityThread
private class Idler implements MessageQueue.IdleHandler {
@Override
public final boolean queueIdle() {
.....
if (a != null) {
mNewActivities = null;
IActivityManager am = ActivityManagerNative.getDefault();
ActivityClientRecord prev;
do {
if (localLOGV) Slog.v(
TAG, "Reporting idle of " + a +
" finished=" +
(a.activity != null && a.activity.mFinished));
if (a.activity != null && !a.activity.mFinished) {
try {
am.activityIdle(a.token, a.createdConfig, stopProfiling);
a.createdConfig = null;
} catch (RemoteException ex) {
// Ignore
}
}
.....
}
调用了IActivityManager的ActivityIdle方法,最终调用了ActivityManagerService的方法2、#ActivityManagerService
@Override
public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
final long origId = Binder.clearCallingIdentity();
synchronized (this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
ActivityRecord r =
mStackSupervisor.activityIdleInternalLocked(token, false, config);
if (stopProfiling) {
if ((mProfileProc == r.app) && (mProfileFd != null)) {
try {
mProfileFd.close();
} catch (IOException e) {
}
clearProfilerLocked();
}
}
}
}
Binder.restoreCallingIdentity(origId);
}
调用了ActivityStackSupervisor的activityIdleInternalLocked方法#ActivityStackSupervisor
final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
Configuration config) {
...

// Stop any activities that are scheduled to do so but have been
// waiting for the next one to start.
for (int i = 0; i < NS; i++) {
r = stops.get(i);
final ActivityStack stack = r.task.stack;
if (stack != null) {
if (r.finishing) {
stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
} else {
stack.stopActivityLocked(r);
}
}
}

...

return r;
}
调用了ActivityStack的stopActivityLocked方法#ActivityStack
final void stopActivityLocked(ActivityRecord r) {
if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, "Stopping: " + r);
if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
|| (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
...
r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
...
}
}
调用了IApplicationThread的方法,通过Binder调用了ApplicationThread的scheduleStopActivity方法。
3、通过hanlder调用了ActivityThread的handleStopActivity方法#ActivityThread
private void handleStopActivity(IBinder token, boolean show, int configChanges) {
.....
performStopActivityInner(r, info, show, true);
.....
}
#ActivityThread
private void performStopActivityInner(ActivityClientRecord r,
StopInfo info, boolean keepShown, boolean saveState) {
.....
//最终调用SecondActivity的onSaveInstance方法
if (!r.activity.mFinished && saveState) {
if (r.state == null) {
callCallActivityOnSaveInstanceState(r);
}
}
//调用Activity的performStop方法
if (!keepShown) {
try {
// Now we are idle.
r.activity.performStop();
......
}
}
4、#Activity
final void performStop() {
.....
mInstrumentation.callActivityOnStop(this);
.....
}
调用了Instrumentation的callActivityOnStop方法#Instrumentation
public void callActivityOnStop(Activity activity) {
activity.onStop();
}
最终调用了Activity的onStop方法总结:ActivityThread向ActivityManagerService传递进程间消息通过ActivityManagerNative,ActivityManagerService向ActivityThread进程间传递消息通过IApplicationThread。


参考:Android开发艺术探索

点击打开链接