转载请注明出处:http://blog.csdn.net/crazy1235/article/details/72236314
startActivity() 到底发生了什么?
onCreate() 是什么时候回调的?
onResume() 又是什么时候回调的?
为什么回调OnResume()之后界面才可见?
PhoneWindow是什么时候创建的?
ActivityThread 与 ApplicationThread有什么关系?
带着这些问题往下看!!!
先来一张大概的程序调用流程图
通常启动一个activity都是通过以下的方式:
startActivity(new Intent(this, MainActivity.class));
跟踪源码到 android.app.Activity.java
@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 {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
不管是调用startActivity() 还是 startActivityForResult(),最终都会调用下面的函数!
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);
}
}
}
在这个方法体内,调用了 Instrumentation 的 execStartActivity() 函数!接收返回的 Instrumentation.ActivityResult 对象!
当返回对象不为空时,调用 ActivityThread 的 sendActivityResult() 用来返回结果!
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
// ...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
只看关键代码。这里又出现一个类 ActivityManagerNative 。
static public IActivityManager getDefault() {
return gDefault.get();
}
private static final Singleton gDefault = new Singleton() {
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;
}
};
Singletion 是系统内部提供的单例的封装类!
第一次调用get()方法时,会回调create() 创建对象,后序调用则直接返回第一次创建的对象!
从这个方法体可以明显的观察出,这是一个 AIDL 操作!
首先从ServiceManager中拿到Binder对象!
然后在 asInterface() 中进行判断,如果调用者与服务端不在同一进程,则返回代理对象!
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);
}
asInterface() 就是用于将服务端的Binder对象转换成客户端所需的AIDL接口类型的对象。如果客户端和服务端处于同一进程,则返回服务端的IActivityManager对象,否则返回代理对象。
代理对象就是ActivityManagerProxy 。
看到这里,会发现这是一个典型的AIDL模式!
只不过这里没有xxx.aidl 文件!
IActivityManager.java 就相当于编译aidl之后生成的类文件,继承 IInterface.java 这个接口!
普通aidl文件编译生成的 Ixxx.java文件中,包含两个内部类,一个是Stub,一个是Proxy!但是在这里分为两个文件!
ActivityManagerNative.java 就相当于Stub,同样是继承Binder类,实现了IActivityManager 。通Stub类一样,里面包含 asInterface(), asBinder(), onTransact() 等函数!
ActivityManagerProxy.java 相当于Proxy(从名称很明显就看的出来)。它是ActivityManagerNative 的内部类!
ActivityManagerService.java 是 ActivityManagerNative.java 的具体实现。也就是说AMS才是服务端的具体实现!
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);
// ... 省略代码
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0); // 远程调用!
reply.readException();
int result = reply.readInt();
reply.recycle();
data.recycle();
return result;
}
@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);
// TODO: Switch to user app stacks here.
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null);
}
ActivirtyStarter 是用来启动activity的!
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, IActivityManager.WaitResult outResult, Configuration config,
Bundle bOptions, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask) {
// ...
final ActivityRecord[] outRecord = new ActivityRecord[1];
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);
// ...
final ActivityRecord launchedActivity = mReusedActivity != null
? mReusedActivity : outRecord[0];
mSupervisor.mActivityMetricsLogger.notifyActivityLaunched(res, launchedActivity);
return res;
}
}
final 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) {
int err = ActivityManager.START_SUCCESS;
// ...
ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
requestCode, componentSpecified, voiceSession != null, mSupervisor, container,
options, sourceRecord);
// ...
doPendingActivityLaunchesLocked(false);
try {
mService.mWindowManager.deferSurfaceLayout();
// !!!
err = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true, options, inTask);
} finally {
mService.mWindowManager.continueSurfaceLayout();
}
postStartActivityUncheckedProcessing(r, err, stack.mStackId, mSourceRecord, mTargetStack);
return err;
}
在这个函数内部又调用了startActivityUnchecked()
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor);
mIntent.setFlags(mLaunchFlags);
mReusedActivity = setTargetStackAndMoveToFrontIfNeeded(mReusedActivity);
if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
resumeTargetStackIfNeeded(); // ...
return START_RETURN_INTENT_TO_CALLER;
}
setTaskFromIntentActivity(mReusedActivity);
if (!mAddingToTask && mReuseTask == null) {
resumeTargetStackIfNeeded();
return START_TASK_TO_FRONT;
}
// 是否要启动新的ActivityTask
boolean newTask = false;
// ...
if (newTask) {
EventLog.writeEvent(
EventLogTags.AM_CREATE_TASK, mStartActivity.userId, mStartActivity.task.taskId);
}
ActivityStack.logStartActivity(
EventLogTags.AM_CREATE_ACTIVITY, mStartActivity, mStartActivity.task);
mTargetStack.mLastPausedActivity = null;
sendPowerHintForLaunchStartIfNeeded(false /* forceSend */);
mTarg`private void resumeTargetStackIfNeeded() {
if (mDoResume) {
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, null, mOptions);
if (!mMovedToFront) {
// Make sure to notify Keyguard as well if we are not running an app transition
// later.
mSupervisor.notifyActivityDrawnForKeyguard();
}
} else {
ActivityOptions.abort(mOptions);
}
mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
}`etStack.startActivityLocked(mStartActivity, newTask, mKeepCurTransition, mOptions);
// ...
mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
mSupervisor.handleNonResizableTaskIfNeeded(
mStartActivity.task, preferredLaunchStackId, mTargetStack.mStackId);
return START_SUCCESS;
}
private void resumeTargetStackIfNeeded() {
if (mDoResume) {
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, null, mOptions);
if (!mMovedToFront) {
// Make sure to notify Keyguard as well if we are not running an app transition
// later.
mSupervisor.notifyActivityDrawnForKeyguard();
}
} else {
ActivityOptions.abort(mOptions);
}
mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
}
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || r.state != RESUMED) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
}
return false;
}
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
// ...
boolean result = false;
try {
// ...
result = resumeTopActivityInnerLocked(prev, options); // !!!
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
在此函数内部调用了 ActivityStackSupervisor.startSpecificActivityLocked()
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
r.task.stack.setLaunchTime(r);
if (app != null && app.thread != null) {
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
// 添加package信息
app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
mService.mProcessStats);
}
// 真正启动activity
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
}
// ...
}
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
final ActivityStack stack = task.stack;
try {
if (app.thread == null) {
throw new RemoteException();
}
// ...
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
} catch (RemoteException e) {
}
return true;
}
app.thread 是 IApplicationThread 类型!
public interface IApplicationThread extends IInterface
而 IApplicationThread 继承IInterface !!!
内部定义了大量关于activity启动,暂停,停止;以及service启动,停止的方法!
既然继承了IInterface,那么猜想肯定是AIDL类型了~ 就像上面的 IActivityManager 一样!
与IApplicationThread 这个IPC 相关的类有以下几个:
IApplicationThread
ApplicationThreadProxy
ApplicationThreadNative
ApplicationThread
ApplicationThreadNative 就是 IApplicationThread 的实现者,但是它是一个抽象类,所以它的子类 ApplicationThread 就是真正的实现者!
ApplicationThread 是 ActivityThread 的内部类!
@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 pendingResults, List 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);
}
方法体最后发送一个消息交给Handler处理!
在ActivityThread内部有一个内部类 H,它继承了 android.os.Handler 。
所以 sendMessage(H.LAUNCH_ACTIVITY, r); 最终要在H类中的 handlerMessage() 函数中进行处理!
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;
这里又调用了ActivityThread类中的 handleLaunchActivity() 函数!
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
// 1. 初始化WindowManagerGlobal
WindowManagerGlobal.initialize();
// 2. 启动activity
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
reportSizeConfigurations(r);
Bundle oldState = r.state;
// 3. resume activity
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
// ...
}
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. 通过类加载器创建activity对象
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader(); // 获取类加载器
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent); // 创建Activity对象
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 {
// 3. 创建Application对象
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
// ...
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);
}
Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
// 4. Activity的初始化操作
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;
// 对activity设置主题
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
// 5. 回调activity的onCreate()方法!
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;
// 6. 回调Activity的onStart()方法
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
// 7. 回调Activity的onRestoreInstanceState()方法
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);
}
}
// 8. 回调Activity的onPostCreate()方法
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;
// 9. 放入集合中!
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;
}
创建Activity对象很简单,系统内部不是通过new对象的方式,而是用类加载器来构建的!
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
return (Activity)cl.loadClass(className).newInstance();
}
接着来看下 makeApplication()
LoadedAPK.java
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
// 当mApplication不为空时,直接返回!
if (mApplication != null) {
return mApplication;
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
try {
java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
"initializeJavaContextClassLoader");
initializeJavaContextClassLoader();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
// 构造Application
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
if (!mActivityThread.mInstrumentation.onException(app, e)) {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
throw new RuntimeException(
"Unable to instantiate application " + appClass
+ ": " + e.toString(), e);
}
}
mActivityThread.mAllApplications.add(app);
mApplication = app; // 赋值
if (instrumentation != null) {
try {
// 回调Application中的 onCreate() 方法
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
if (!instrumentation.onException(app, e)) {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
throw new RuntimeException(
"Unable to create application " + app.getClass().getName()
+ ": " + e.toString(), e);
}
}
}
//...
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
return app;
}
从上面的过程可以看出,当Application 已经被创建过了,就直接返回,不在创建新的Application!
当mApplication为空时,通过 Instrumentation 来创建!
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
return newApplication(cl.loadClass(className), context);
}
static public Application newApplication(Class> clazz, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app = (Application)clazz.newInstance();
app.attach(context);
return app;
}
与创建Activity对象一样,也是通过 类加载器 来实现的 !
创建了Application之后,调用 callApplicationOnCreate()
public void callApplicationOnCreate(Application app) {
app.onCreate();
}
从而回调了 Application.onCreate() 函数!
在回到 performLaunchActivity() 方法体中!
Activity和Application都存在了,接着调用了 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,
Window window) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
// 创建PhoneWindow对象
mWindow = new PhoneWindow(this, window);
mWindow.setWindowControllerCallback(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);
}
mUiThread = Thread.currentThread();
// ...
}
从这里可以看出来, PhoneWindow就是在attach() 函数中创建的 !回到了blog开头的第五个问题!
再次回到performLaunchActivity() 函数内
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
对应到 Instrumentation 类中:
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}
接着调用了Activity中的方法:
final void performCreate(Bundle icicle) {
restoreHasCurrentPermissionRequest(icicle);
onCreate(icicle); // onCreate
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
restoreHasCurrentPermissionRequest(icicle);
onCreate(icicle, persistentState); // onCreate
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
OK,到这里就能看出Activity中的生命周期函数onCreate()被回调了!
onCreate() 这个生命周期函数就是在 performLaunchActivity() 内部,调用了mInstrumentation.callActivityOnCreate() 函数,进而进行回调的!
if (r.isPersistable()) {
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnPostCreate(activity, r.state)
}
紧接着调用了callActivityOnPostCreate()
public void callActivityOnPostCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
activity.onPostCreate(icicle, persistentState);
}
这里正好回调了生命周期函数 onPostCreate()
OK,至此从调用startActivity() 到activity启动并回调onCreate() 的过程就分析完毕了!
下面来看看Activity 是什么时候可见的!
我们通常会在onCreate()生命周期中,设置我们自己的布局文件
setContentView(R.layout.activity_test_view);
关于setContentView() 系统内部流程,参考这篇blog: setContentView() 究竟都做了什么?
我们在上面分析代码的时候,分析到 ActivityThread.handleLaunchActivity() 方法是,说先调用的是 performLaunchActivity()(内部回调了onCreate()),接着调用了 handleResumeActivity() 。看方法名字就知道跟onResume() 有关系了!
ActivityThread.handleResumeActivity()
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
// 1. 获取 ActivityClientRecord 对象
r = performResumeActivity(token, clearHide, reason);
if (r != null) {
final Activity a = r.activity;
// ...
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 (r.mPreserveWindow) {
a.mWindowAdded = true;
r.mPreserveWindow = false;
ViewRootImpl impl = decor.getViewRootImpl();
if (impl != null) {
impl.notifyChildRebuilt();
}
}
if (a.mVisibleFromClient && !a.mWindowAdded) {
a.mWindowAdded = true;
// 添加ViewManager中
wm.addView(decor, l);
}
} else if (!willBeVisible) {
r.hideForNow = true;
}
// ...
if (!r.activity.mFinished && willBeVisible
&& r.activity.mDecor != null && !r.hideForNow) {
// ...
if (r.activity.mVisibleFromClient) {
r.activity.makeVisible(); // 重要函数!
}
}
} else {
// ...
}
}
在函数内部,首先将decorView设置为INVISIABLE,不可见状态!
当Activity 满足 (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) 这几个条件时吗,调用了 Activity.makeVisiable() 。
Activity.makeVisiable()
void makeVisible() {
if (!mWindowAdded) {
ViewManager wm = getWindowManager();
wm.addView(mDecor, getWindow().getAttributes());
mWindowAdded = true;
}
mDecor.setVisibility(View.VISIBLE);
}
在这里将decoerView设置为可见状态!
在回过头来看 performResumeActivity()
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide, String reason) {
if (r != null && !r.activity.mFinished) {
if (clearHide) {
r.hideForNow = false;
r.activity.mStartedActivity = false;
}
try {
//...
r.activity.performResume();
//...
} catch (Exception e) {
//...
}
}
return r;
}
方法内部调用了 Activity.performResume()
final void performResume() {
// ...
mInstrumentation.callActivityOnResume(this);
// ...
}
Instrumentation.callActivityOnResume()
public void callActivityOnResume(Activity activity) {
activity.mResumed = true;
activity.onResume();
// ..
}
这里回调了Activity的生命周期函数 onResume()
通过上面的分析,就会发现在系统回调onResume()之后界面才可见!!!