阅读 1432

基于8.0源码解析:Activity启动流程

欢迎关注我的公众号:

欢迎关注我的公众号
--- 先贴下图,有个心里预期。


基于8.0源码解析:Activity启动流程

本文大概有以下方面:

  • 1、onPause()方法执行;
  • 2、onCreate()方法执行;
  • 3、onStart()方法执行;
  • 4、onResum()方法执行;
  • 5、onStop()方法执行;
  • 6、onSaveInstance()方法执行;
  • 7、总结;

1. onPause()方法的执行

调用startActivity,会执行Activity中的startActivity

@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);
}
}
复制代码

最后会调用startActivityForResult,然后会调用mInstrumentation的execStartActivity

mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
复制代码

mInstrumentation是android系统中启动activity的一个实际操作类,也就是说activity在应用进程端的启动实际上就是instrumentation执行的。实际上activity的启动分为应用进程端的启动和systemserver服务端的启动。多个应用进程相互配合最终完成了activity在系统中的启动,而在应用进程端的启动实际的操作类就是intrumentation来执行的。于是发现了这个方法

int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target, requestCode, 0, null, options);
复制代码

ActivityManagerNative.getDefault() 是什么?到ActivityManagerNative中看一眼

static public IActivityManager getDefault() {
return gDefault.get();
}
复制代码

gDefault.get()又是什么?先看gDefault

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;
}
};
}
复制代码

可以发现启动了IActivityManager am = asInterface(b);然后看asInterface(b)的实现:

static public IActivityManager asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IActivityManager in =
(IActivityManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}

return new ActivityManagerProxy(obj);
}
复制代码

最后直击返回了ActivityManagerProxy。二ActivityManagerProxy继承自IActivityManager,IActivityManager extends IInterface。应用进程与systemserver进程属于两个不同的进程,进程之间需要通讯,android系统采取了自身设计的binder机制,这里的activityManagerProxy和ActivityManagerNative都是继承IAcitivityManager,而Systemserver进程中的ActivityManagerServise对象则继承于ActivityManagerNative Binder --> ActivityManagerNative/ActivityManagerProxy -->ActivityManagerService这样ActivityManagerNative和ActivityManagerProxy相当于一个binder的客户端,而ActivityManagerService相当于Binder的服务端。这样当ActivityManagerNative调用接口方法的时候底层通过Binder driver就会将请求数据与请求传递给server端,并在server端进行具体的接口逻辑。binder机制是单向的,异步的。继续看

int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target, requestCode, 0, null, options);
复制代码

可以看到涉及到了binder数据传输机制,说明会调用systemserver进程

public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(caller != null ? caller.asBinder() : null);
data.writeString(callingPackage);
intent.writeToParcel(data, 0);
data.writeString(resolvedType);
data.writeStrongBinder(resultTo);
data.writeString(resultWho);
data.writeInt(requestCode);
data.writeInt(startFlags);
if (profilerInfo != null) {
data.writeInt(1);
profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
data.writeInt(0);
}
if (options != null) {
data.writeInt(1);
options.writeToParcel(data, 0);
} else {
data.writeInt(0);
}
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
reply.readException();
int result = reply.readInt();
reply.recycle();
data.recycle();
return result;
}
复制代码

ActivityManagerService中查看startActivity

@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());
}
复制代码

又调用了startActivityAsUser

然后调用到了ActivityStarter的startActivityMayWait方法

然后调用startActivityLocked然后调用 startActivity其中又调用了

result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
1003                    startFlags, doResume, options, inTask, outActivity);
复制代码

最后调用到

if (mDoResume) {
1159                mSupervisor.resumeFocusedStackTopActivityLocked();
1160            }
复制代码

查看这个方法,最后发现其中调用了mFocusedStack.resumeTopActivityUncheckedLocked(null, null);

boolean resumeFocusedStackTopActivityLocked(
2060            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
2061        if (targetStack != null && isFocusedStack(targetStack)) {
2062            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
2063        }
2064        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
2065        if (r == null || r.state != RESUMED) {
2066            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
2067        } else if (r.state == RESUMED) {
2068            // Kick off any lingering app transitions form the MoveTaskToFront operation.
2069            mFocusedStack.executeAppTransition(targetOptions);
2070        }
2071        return false;
2072    }
复制代码

查看其中的方法

继续跟mStackSupervisor.checkReadyForSleepLocked();发现其中调用了 startPausingLocked(false, true, null, false);然后去 startPausingLocked(false, true, null, false)中看:这个方法就是让系统中的栈中的activity执行onPause方法。其中 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,userLeaving,prev.configChangeFlags,pauseImmediately);这里的thread是一个IApplicationThread类型的对象,而在ActivityThread中也有一个ApplicationThread类,其继承了IApplicationTHread,并且都是Binder对象。那么这里的IApplication是一个Binder的client端,而ActivityThread中的APplictionThread中的ApplicationThread中是的Binder对象的server端。所以这里的thrad。schedulePauseActivity实际上调用的就是ApplicationThread的SchedulePauseActivity方法。

回到AcitivityThread中:

public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
int seq = getLifecycleSeq();
if (DEBUG_ORDER) Slog.d(TAG, "pauseActivity " + ActivityThread.this
+ " operation received seq: " + seq);
sendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),
configChanges,
seq);
}
复制代码

其中sendMessage是继承自Handler的H发送了PAUSE_ACTIVITY_FINISHING的msg,于是去H中的handleMessage中找对应的方法:

case PAUSE_ACTIVITY_FINISHING: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
SomeArgs args = (SomeArgs) msg.obj;
handlePauseActivity((IBinder) args.arg1, true, (args.argi1 & USER_LEAVING) != 0,
args.argi2, (args.argi1 & DONT_REPORT) != 0, args.argi3);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
复制代码

其中调用了handlePauseActivity方法:看到其中调用了performPauseActivity(token, finished, r.isPreHoneycomb(), "handlePauseActivity")方法:

final Bundle performPauseActivity(IBinder token, boolean finished,
boolean saveState, String reason) {
ActivityClientRecord r = mActivities.get(token);
return r != null ? performPauseActivity(r, finished, saveState, reason) : null;
}
复制代码

这其中又调用了performPauseActivity的重载方法:方法中又调用了 performPauseActivityIfNeeded(r, reason)方法,我们到这个方法中看一眼:

private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
if (r.paused) {
// You are already paused silly...
return;
}

try {
r.activity.mCalled = false;
mInstrumentation.callActivityOnPause(r.activity);
EventLog.writeEvent(LOG_AM_ON_PAUSE_CALLED, UserHandle.myUserId(),
r.activity.getComponentName().getClassName(), reason);
if (!r.activity.mCalled) {
throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
+ " did not call through to super.onPause()");
}
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException("Unable to pause activity "
+ safeToComponentShortString(r.intent) + ": " + e.toString(), e);
}
}
r.paused = true;
}
复制代码

终于看到了mInstrumentation.callActivityOnPause(r.activity);然后我们去mInstrumentation中去找对应的方法:

public void callActivityOnPause(Activity activity) {
activity.performPause();
}
复制代码

我们看到是调用了 activity.performPause(),于是我们回到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()方法,那么就是在这里调用了onPause()方法,让栈顶的activity处于onpause。也就是说我们在启动一个activty的时候最先被执行的是栈顶的activity的onpause方法;handlePauseActivity最后又掉用了ActivityManagerNative.getDefault().activityPaused(token),这是应用进程告诉服务进程,栈顶的activity已经弯沉onpause方法,通过binder机制,这个方法最终会调用到ActivityManagerServise的activityPaused方法执行。

@Override
7246    public final void activityPaused(IBinder token) {
7247        final long origId = Binder.clearCallingIdentity();
7248        synchronized(this) {
7249            ActivityStack stack = ActivityRecord.getStackLocked(token);
7250            if (stack != null) {
7251                stack.activityPausedLocked(token, false);
7252            }
7253        }
7254        Binder.restoreCallingIdentity(origId);
7255    }
7256
复制代码

该方法内部调用了activityPausedLocked方法,然后执行了 completePauseLocked(true /* resumeNext /, null / resumingActivity */);

2. onCreate()方法的执行

这里面又调用了 mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);然后对应方法又调用targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);对应的方法又去调用 result = resumeTopActivityInnerLocked(prev, options);这个方法最后调用了 mStackSupervisor.startSpecificActivityLocked(next, true, false);(这几个和前面类似,只是代码片段太多,估计贴出来你们都晕头转向了,所以省略吧)

void startSpecificActivityLocked(ActivityRecord r,
1553            boolean andResume, boolean checkConfig) {
1554        // Is this activity's application already running?
1555        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
1556                r.info.applicationInfo.uid, true);
1557
1558        r.getStack().setLaunchTime(r);
1559
1560        if (app != null && app.thread != null) {
1561            try {
1562                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
1563                        || !"android".equals(r.info.packageName)) {
1564                    // Don't add this if it is a platform component that is marked
1565                    // to run in multiple processes, because this is actually
1566                    // part of the framework so doesn't make sense to track as a
1567                    // separate apk in the process.
1568                    app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
1569                            mService.mProcessStats);
1570                }
1571                realStartActivityLocked(r, app, andResume, checkConfig);
1572                return;
1573            } catch (RemoteException e) {
1574                Slog.w(TAG, "Exception when starting activity "
1575                        + r.intent.getComponent().flattenToShortString(), e);
1576            }
1577
1578            // If a dead object exception was thrown -- fall through to
1579            // restart the application.
1580        }
1581
1582        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
1583                "activity", r.intent.getComponent(), false, false, true);
1584    }
复制代码

这里判断activity所需的进程是否已经启动,若启动的话调用realStartActivityLocked(r, app, andResume, checkConfig);看一下这个方法,否则调用 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,"activity", r.intent.getComponent(), false, false, true):在这其中调用了app.thread.scheduleLaunchActivity

而当activity所需要的进程未启动则会调用 startProcessLocked(app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);然后这个方法又调用了

startResult = Process.start(entryPoint,
3926                        app.processName, uid, uid, gids, debugFlags, mountExternal,
3927                        app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
3928                        app.info.dataDir, invokeWith, entryPointArgs);
复制代码

然后就到了ZygoteProcess中的start方法:

public final Process.ProcessStartResult start(final String processClass,
196                                                  final String niceName,
197                                                  int uid, int gid, int[] gids,
198                                                  int debugFlags, int mountExternal,
199                                                  int targetSdkVersion,
200                                                  String seInfo,
201                                                  String abi,
202                                                  String instructionSet,
203                                                  String appDataDir,
204                                                  String invokeWith,
205                                                  String[] zygoteArgs) {
206        try {
207            return startViaZygote(processClass, niceName, uid, gid, gids,
208                    debugFlags, mountExternal, targetSdkVersion, seInfo,
209                    abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
210        } catch (ZygoteStartFailedEx ex) {
211            Log.e(LOG_TAG,
212                    "Starting VM process through Zygote failed");
213            throw new RuntimeException(
214                    "Starting VM process through Zygote failed", ex);
215        }
216    }
复制代码

对应方法太长于是就截取最关键的代码

synchronized(mLock) {
431            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
432        }
复制代码

这最终调用了zygote并通过socket通信的方式让那个zygote进程fork出一个新的进程,并根据我们刚刚传递的“android.app.ActivityTHread"字符串,发射出该对象并执行activitythread的main方法。应用进程被产创建之后,首先执行的是ActivityThead的main方法。main方法中

ActivityThread thread = new ActivityThread();
thread.attach(false);
复制代码

attach方法又调用了

final IActivityManager mgr = ActivityManagerNative.getDefault();
try {
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
复制代码

于是又回到了ActivityManagerService中

@Override
7021    public final void attachApplication(IApplicationThread thread) {
7022        synchronized (this) {
7023            int callingPid = Binder.getCallingPid();
7024            final long origId = Binder.clearCallingIdentity();
7025            attachApplicationLocked(thread, callingPid);
7026            Binder.restoreCallingIdentity(origId);
7027        }
7028    }
7029
复制代码

最终调用到

app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
1468                    System.identityHashCode(r), r.info,
1469                    // TODO: Have this take the merged configuration instead of separate global and
1470                    // override configs.
1471                    mergedConfiguration.getGlobalConfiguration(),
1472                    mergedConfiguration.getOverrideConfiguration(), r.compat,
1473                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
1474                    r.persistentState, results, newIntents, !andResume,
1475                    mService.isNextTransitionForward(), profilerInfo);
复制代码

与onPause类似,这里也是通过IApplicationThread的方法实现的,这里调用的scheduleLaunchActivity方法最终调用的是ActivityThread中的 scheduleLaunchActivity方法同样的到了H中的handleMessage:

case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
复制代码

然后我们去看handleLaunchActivity,其中又调用了Activity a = performLaunchActivity(r, customIntent);

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

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

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

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

if (activity != null) {
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
+ r.activityInfo.name + " with config " + config);
Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
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);

if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}

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) {
activity.performStart();
r.stopped = false;
}
if (!r.activity.mFinished) {
if (r.isPersistable()) {
if (r.state != null || r.persistentState != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
r.persistentState);
}
} else if (r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
if (!r.activity.mFinished) {
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnPostCreate(activity, r.state);
}
if (!activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onPostCreate()");
}
}
}
r.paused = true;

mActivities.put(r.token, r);

} catch (SuperNotCalledException e) {
throw e;

} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to start activity " + component
+ ": " + e.toString(), e);
}
}

return activity;
}
复制代码

mInstrumentation.newActivity通过反射方法创建了Activity,最后调用了mInstrumentation.callActivityOnCreate方法然后我们去Instrumentation中看:

public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
复制代码

我们去看Activity中的activity.performCreate(icicle);

final void performCreate(Bundle icicle) {
restoreHasCurrentPermissionRequest(icicle);
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
复制代码

3. onstart()方法的执行

好吧,总算看到了Activity的onCreate方法,再去ActivityThread的performLaunchActivty中在调用了callActivityOnCreate方法后又调用了activity.performStart();方法

if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
复制代码

去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();

// This property is set for all builds except final release
boolean isDlwarningEnabled = SystemProperties.getInt("ro.bionic.ld.warning", 0) == 1;
boolean isAppDebuggable =
(mApplication.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;

if (isAppDebuggable || isDlwarningEnabled) {
String dlwarning = getDlWarning();
if (dlwarning != null) {
String appName = getApplicationInfo().loadLabel(getPackageManager())
.toString();
String warning = "Detected problems with app native libraries\n" +
"(please consult log for detail):\n" + dlwarning;
if (isAppDebuggable) {
new AlertDialog.Builder(this).
setTitle(appName).
setMessage(warning).
setPositiveButton(android.R.string.ok, null).
setCancelable(false).
show();
} else {
Toast.makeText(this, appName + "\n" + warning, Toast.LENGTH_LONG).show();
}
}
}

mActivityTransitionState.enterReady(this);
}
复制代码

看到了mInstrumentation.callActivityOnStart(this);看一眼这个方法做了什么:

public void callActivityOnStart(Activity activity) {
activity.onStart();
}
复制代码

尼玛,这么久终于等到onstart方法了。然后我们再回到ActivityThread中的handleLaunchActivty中看到PerformLaynchActivty方法之后调用了

handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
复制代码

4. onResume()方法的执行

然后就是调用r = performResumeActivity(token, clearHide, reason);然后再调用 r.activity.performResume();这个方法在Activity中,于是又跑到activty类中:

final void performResume() {
performRestart();

mFragments.execPendingActions();

mLastNonConfigurationInstances = null;

mCalled = false;
// mResumed is set by the instrumentation
mInstrumentation.callActivityOnResume(this);
if (!mCalled) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onResume()");
}

// invisible activities must be finished before onResume() completes
if (!mVisibleFromClient && !mFinished) {
Log.w(TAG, "An activity without a UI must call finish() before onResume() completes");
if (getApplicationInfo().targetSdkVersion
> android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
throw new IllegalStateException(
"Activity " + mComponent.toShortString() +
" did not call finish() prior to onResume() completing");
}
}

// Now really resume, and install the current status bar and menu.
mCalled = false;

mFragments.dispatchResume();
mFragments.execPendingActions();

onPostResume();
if (!mCalled) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onPostResume()");
}
}
复制代码

又看到了mInstrumentation.callActivityOnResume(this);去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();

###至此,一个activty的启动过程完成。

5. onStop()方法的执行

###下面就是另一个activty的onstop过程:在ActivityThread中的handleresumeActivty中:有这样一段代码:

if (!r.onlyLocalRequest) {
r.nextIdle = mNewActivities;
mNewActivities = r;
if (localLOGV) Slog.v(
TAG, "Scheduling idle handler for " + r);
Looper.myQueue().addIdleHandler(new Idler());
}
复制代码

先把这段代码贴出来:

private class Idler implements MessageQueue.IdleHandler {
@Override
public final boolean queueIdle() {
ActivityClientRecord a = mNewActivities;
boolean stopProfiling = false;
if (mBoundApplication != null && mProfiler.profileFd != null
&& mProfiler.autoStopProfiler) {
stopProfiling = true;
}
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) {
throw ex.rethrowFromSystemServer();
}
}
prev = a;
a = a.nextIdle;
prev.nextIdle = null;
} while (a != null);
}
if (stopProfiling) {
mProfiler.stopProfiling();
}
ensureJitEnabled();
return false;
}
}
复制代码

看到其中调用了am.activityIdle(a.token, a.createdConfig, stopProfiling);按照Binder机制,这段代码执行在ActivityManagerService中,

@Override
7031    public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
7032        final long origId = Binder.clearCallingIdentity();
7033        synchronized (this) {
7034            ActivityStack stack = ActivityRecord.getStackLocked(token);
7035            if (stack != null) {
7036                ActivityRecord r =
7037                        mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */,
7038                                false /* processPausingActivities */, config);
7039                if (stopProfiling) {
7040                    if ((mProfileProc == r.app) && (mProfileFd != null)) {
7041                        try {
7042                            mProfileFd.close();
7043                        } catch (IOException e) {
7044                        }
7045                        clearProfilerLocked();
7046                    }
7047                }
7048            }
7049        }
7050        Binder.restoreCallingIdentity(origId);
7051    }
复制代码
这其中有一段代码:mStackSupervisor.activityIdleInternalLocked先贴下这个方法的代码:在这其中,又调用了 stack.stopActivityLocked(r);r.app.thread.scheduleStopActivity这个熟悉吧,这个肯定又是去ActivityThread中,还是Binder机制,于是又回到ActivityThread中:
public final void scheduleStopActivity(IBinder token, boolean showWindow,
int configChanges) {
int seq = getLifecycleSeq();
if (DEBUG_ORDER) Slog.d(TAG, "stopActivity " + ActivityThread.this
+ " operation received seq: " + seq);
sendMessage(
showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
token, 0, configChanges, seq);
}
复制代码

还是去H中看对应的case:

case STOP_ACTIVITY_SHOW: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
SomeArgs args = (SomeArgs) msg.obj;
handleStopActivity((IBinder) args.arg1, true, args.argi2, args.argi3);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
复制代码

再追踪,发现handleStopActivty中又调用了performStopActivityInner(r, info, show, true, "handleStopActivity");然后对应的有看到r.activity.performStop(false /preserveWindow/);回到Activty中:又调用了mInstrumentation.callActivityOnStop(this);贴代码:

public void callActivityOnStop(Activity activity) {
activity.onStop();
}
复制代码

激动不,终于调用到了onstop方法。

6. OnSaveInstanceStat()方法的执行

值得注意的是在 r.activity.performStop();之前调用了callCallActivityOnSaveInstanceState(r);

private void callCallActivityOnSaveInstanceState(ActivityClientRecord r) {
r.state = new Bundle();
r.state.setAllowFds(false);
if (r.isPersistable()) {
r.persistentState = new PersistableBundle();
mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
}
}
复制代码

然后又调用到了mInstrumentation.callActivityOnSaveInstanceState

public void callActivityOnSaveInstanceState(Activity activity, Bundle outState,
PersistableBundle outPersistentState) {
activity.performSaveInstanceState(outState, outPersistentState);
}
复制代码

回到Activity中:

final void performSaveInstanceState(Bundle outState) {
onSaveInstanceState(outState);
saveManagedDialogs(outState);
mActivityTransitionState.saveState(outState);
storeHasCurrentPermissionRequest(outState);
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onSaveInstanceState " + this + ": " + outState);
}
复制代码

onSaveInstanceState(outState);就是在这里被调起来的,所以通常问onSaveInstanceState在什么时机被调起,就是onstop之前。至此,所有的activity启动流程我们都分析完成了。

7. 总结

下面总结一下:

    1. Activity启动涉及到多个进程之间的通讯,这里主要是ActivityThead和ActivityManagerService之间的通讯
    1. ActivityThread向ActivityManagerService进程间消息通过ActivityManagerNative,ActivityManagerService向ActivityThread进程间传递消息通过IApplicationThread
    1. ActivityManagerService保存完信息之后会将系统栈顶的activity执行onPause操作,并且IApplication进程间通讯告诉应用程序执行当前栈顶Activity的onPause方法。
    1. ActivityThead接收到SystemServer的消息后会统一交给自身定义的Handler对象处理;
    1. ActivityManagerService将执行创建Activity的通知告知ActivityTHread,通过反射机制创建出Activity对象,并执行Activity的oncreate方法,onstart方法,onresume方法。
    1. ActivityThread执行完成onresume方法后告知ActivityManagerServise onresume方法完成,执行栈顶的onstop方法。
评论