Android绘制流程窗口启动流程分析(上)

原文链接:https://www.cnblogs.com/tiger-wang-ms/p/6517048.html

源码分析篇 - Android绘制流程(一)窗口启动流程分析

Activity、View、Window之间的关系可以用以下的简要UML关系图表示,在这里贴出来,比较能够帮组后面流程分析部分的阅读。


一、Activity的启动流程

在startActivity()后,经过一些逻辑流程会通知到ActivityManagerService(后面以AMS简称),AMS接收到启动acitivty的请求后,会通过跨进程通信调用AcitivtyThread.handleLauncherActivity()方法,我们从这里开始分析,首先来看handleLauncherActivity()方法。

`private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {

...// Initialize before creating the activity

WindowManagerGlobal.initialize();

Activitya = performLaunchActivity(r, customIntent);

if (a != null) {         r.createdConfig = new Configuration(mConfiguration);         reportSizeConfigurations(r);         Bundle oldState = r.state;

//该方法会调用到Activity的onResume()方法         handleResumeActivity(r.token, false, r.isForward,               !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

...

}

...

}`

这里重点关注三个方法(加粗的地方),首先来看WindowManagerGlobal.initialize(),WindowManagerGlobal是单例模式的,一个进程内只有一个,这里调用该类的初始化方法,后续我们再对该类的作用和相关方法进行分析;第三个是在创建好Activity后调用Acitivty的onResume()方法。这里我们来看需关注的第二个方法performLaunchActivity(),代码如下。

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {      ...//通过反射方式创建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)) {thrownewRuntimeException("Unable to instantiate activity "+ component                    +": "+ e.toString(), e);            }        }try{            ...if(activity !=null) {                Context appContext = createBaseContextForActivity(r, activity);                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());                Configuration config =newConfiguration(mCompatConfiguration);if(r.overrideConfig !=null) {                    config.updateFrom(r.overrideConfig);                }if(DEBUG_CONFIGURATION) Slog.v(TAG,"Launching activity "+ r.activityInfo.name +" with config "+ config);                Windowwindow=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);            ...//调用acitivity的onCreate()方法if(r.isPersistable()) {                                   mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);                           }else{                                   mInstrumentation.callActivityOnCreate(activity, r.state);                           }          ...       }returnactivity;    }

这个方法主要是读取Acitivity这里利用反射创建出ActivityClientRecord所要求的Activity对象,然后调用了acitivity.attach()方法。注意attach()传入的参数有很多,在performLacunchActivity()方法流程中,调用attach()方前,我们省略掉的步骤基本都在为这些参数做准备,attach()方法的作用其实就是将这些参数配置到新创建的Activity对象中;而在attach之后则会回调到acitivity的onCreate()方法。我们进入Activity.java类详细来看下attach方法。

此外,在attach之前会初始化一个Window对象,Window.java是一个抽象类,代表了一个矩形不可见的容器,主要负责加载显示界面,每个Activity都会对应了一个Window对象。如果ActivityClientRecord.mPendingRevomeWindow变量中已经保存了一个Window对象,则会在后面的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*/);    mWindow =newPhoneWindow(this,window);//(1)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);    }     ...//初始化Acitity相关属性mWindow.setWindowManager(            (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),            mToken, mComponent.flattenToString(),            (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) !=0);//(2)if(mParent !=null) {        mWindow.setContainer(mParent.getWindow());    }    mWindowManager = mWindow.getWindowManager();    mCurrentConfig = config;}`

 重点关注初始化window对象的操作,首先创建了PhoneWindow对象为activity的mWindow变量,在创建时传入了上一个activity对应的window对象,之后又将这个acitivity设置为window对象的回调。Activity中很多操作view相关的方法,例如setContentView()、findViewById()、getLayoutInflater()等,实际上都是直接调用到PhoneWindow里面的相关方法。创建完acitivty对应的PhoneWindow之后便会调用setWindowManager()方法。首先来看PhonewWindow构造方法。

publicPhoneWindow(Context context, Window preservedWindow){this(context);// Only main activity windows use decor context, all the other windows depend on whatever// context that was given to them.mUseDecorContext =true;if(preservedWindow !=null) {//快速重启activity机制mDecor = (DecorView) preservedWindow.getDecorView();            mElevation = preservedWindow.getElevation();            mLoadElevation =false;            mForceDecorInstall =true;// If we're preserving window, carry over the app token from the preserved// window, as we'll be skipping the addView in handleResumeActivity(), and// the token will not be updated as for a new window.getAttributes().token = preservedWindow.getAttributes().token;        }// Even though the device doesn't support picture-in-picture mode,// an user can force using it through developer options.booleanforceResizable = Settings.Global.getInt(context.getContentResolver(),                DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES,0) !=0;        mSupportsPictureInPicture = forceResizable || context.getPackageManager().hasSystemFeature(                PackageManager.FEATURE_PICTURE_IN_PICTURE);    }

点击下方链接免费获取Android进阶资料:

https://shimo.im/docs/tXXKHgdjPYj6WT8d/

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355