深入理解WMS(二):Dialog与Toast源码解析

本文详细分析了Android中Activity的启动过程,从ActivityThread的performLaunchActivity方法开始,通过类加载器获取Activity实例,讲解了Window和PhoneWindow的创建、DecorView的初始化和添加,以及Dialog和Toast的Window创建流程,强调了Handler在Toast中的重要角色。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值