…
Activity的启动过程很复杂,最终是有ActivityThread中的performLaunchActivity方法来完成的,看上图源码可以看出performLaunchActivity是通过类加载器获得Activity的实例的。然后调动Activity的attach方法为其关联运行过程中所依赖的一系列上下文环境变量。
在Activity的attach方法里,
-
系统会创建Activity所属的Window对象并为其设置回调接口,这里Window对象实际上是PhoneWindow。
-
给Activity初始化各种参数,如mUiThread等
-
给PhoneWindow设置WindowManager,实际上设置的是WindowManagerImpl:
下图给出一部分源码,有兴趣的同学还是直接看源码。
…
mWindow = new PhoneWindow(this, window, activityConfigCallback);
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();
mMainThread = aThread;
mInstrumentation = instr;
mToken = token;
mIdent = ident;
mApplication = application;
mIntent = intent;
mReferrer = referrer;
mComponent = intent.getComponent();
mActivityInfo = info;
mTitle = title;
mParent = parent;
mEmbeddedID = id;
mLastNonConfigurationInstances = lastNonConfigurationInstances;
if (voiceInteractor != null) {
if (lastNonConfigurationInstances != null) {
mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
} else {
mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
Looper.myLooper());
}
}
mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
if (mParent != null) {
mWindow.setContainer(mParent.getWindow());
}
mWindowManager = mWindow.getWindowManager();
mCurrentConfig = config;\
mWindow.setColorMode(info.colorMode);
…
由于Activity实现了Window的Callback接口,因此当Window接收到外界的状态改变时就会回调Activity的方法。Callback接口中的方法很多,但是有几个却是我们都非常熟悉的,比如onAttachedToWindow、onDetachedFromWindow、dispatchTouchEvent,等等。
public interface Callback {
public boolean dispatchKeyEvent(KeyEvent event);
public boolean dispatchKeyShortcutEvent(KeyEvent event);
public boolean dispatchTouchEvent(MotionEvent event);
public boolean dispatchTrackballEvent(MotionEvent event);
public boolean dispatchGenericMotionEvent(MotionEvent event);
…
到这里Window已经创建完成了,但是像之前文章说过的一样,只有Window其实只是一个空的架子,还需要View才能真正是出现视图。Activity的视图是怎么加到Window中的呢?这里就得说道一个我们很熟悉的方法setContentView。
…
/**
-
Set the activity content from a layout resource. The resource will be
-
inflated, adding all top-level views to the activity.
-
@param layoutResID Resource ID to be inflated.
-
@see #setContentView(android.view.View)