Android中Window添加View的底層原理
一、WIndow和windowManager
Window是一個(gè)抽象類,它的具體實(shí)現(xiàn)是PhoneWindow,創(chuàng)建一個(gè)window很簡(jiǎn)單,只需要?jiǎng)?chuàng)建一個(gè)windowManager即可,window具體實(shí)現(xiàn)在windowManagerService中,windowManager和windowManagerService的交互是一個(gè)IPC的過(guò)程。
下面是用windowManager的例子:
mFloatingButton = new Button(this);
mFloatingButton.setText( "window");
mLayoutParams = new WindowManager.LayoutParams(
LayoutParams. WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0,
PixelFormat. TRANSPARENT);
mLayoutParams. flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
| LayoutParams. FLAG_NOT_FOCUSABLE
| LayoutParams. FLAG_SHOW_WHEN_LOCKED;
mLayoutParams. type = LayoutParams. TYPE_SYSTEM_ERROR;
mLayoutParams. gravity = Gravity. LEFT | Gravity. TOP;
mLayoutParams. x = 100;
mLayoutParams. y = 300;
mFloatingButton.setOnTouchListener( this);
mWindowManager.addView( mFloatingButton, mLayoutParams);
flags和type兩個(gè)屬性很重要,下面對(duì)一些屬性進(jìn)行介紹,首先是flags:
FLAG_NOT_TOUCH_MODAL表示不需要獲取焦點(diǎn),也不需要接收各種輸入,最終事件直接傳遞給下層具有焦點(diǎn)的window。
FLAG_NOT_FOCUSABLE:在此window外的區(qū)域單擊事件傳遞到底層window中。當(dāng)前的區(qū)域則自己處理,這個(gè)一般都要設(shè)置,很重要。
FLAG_SHOW_WHEN_LOCKED :開(kāi)啟可以讓window顯示在鎖屏界面上。
再來(lái)看下type這個(gè)參數(shù):
window有三種類型:應(yīng)用window,子window,系統(tǒng)window。應(yīng)用類對(duì)應(yīng)一個(gè)Activity,子Window不能單獨(dú)存在,需要附屬在父Window上,比如常用的Dialog。系統(tǒng)Window是需要聲明權(quán)限再創(chuàng)建的window,如toast等。
window有z-ordered屬性,層級(jí)越大,越在頂層。應(yīng)用window層級(jí)1-99,子window1000-1999,系統(tǒng)2000-2999。這此層級(jí)對(duì)應(yīng)著windowManager的type參數(shù)。系統(tǒng)層級(jí)常用的有兩個(gè)TYPE_SYSTEM_OVERLAY或者TYPE_SYSTEM_ERROR。比如想用TYPE_SYSTEM_ERROR,只需
mLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR。還要添加權(quán)限<uses-permission andorid:name="android.permission.SYSTEM_ALERT_WINDOW"/>。
有了對(duì)window的基本認(rèn)識(shí)之后,我們來(lái)看下它底層如何實(shí)現(xiàn)加載View的。
二、window的創(chuàng)建
其實(shí)Window的創(chuàng)建跟之前我寫(xiě)的一篇博客LayoutInflater源碼分析有點(diǎn)相似。Window的創(chuàng)建是在Activity創(chuàng)建的attach方法中,通過(guò)PolicyManager的makeNewWindow方法。Activity中實(shí)現(xiàn)了Window的Callback接口,因此當(dāng)window狀態(tài)改變時(shí)就會(huì)回調(diào)Activity方法。如onAttachedToWindow等。PolicyManager的真正實(shí)現(xiàn)類是Policy,看下它的代碼:
public Window makeNewWindow(Context context) {
return new PhoneWindow(context);
}
到此Window創(chuàng)建完成。
下面分析view是如何附屬到window上的。看Activity的setContentView方法。
public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
兩部分,設(shè)置內(nèi)容和設(shè)置ActionBar。window的具體實(shí)現(xiàn)是PhoneWindow,看它的setContent。
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
看到了吧,又是分析它。
這里分三步執(zhí)行:
1.如果沒(méi)有DecorView,在installDecor中的generateDecor()創(chuàng)建DecorView。之前就分析過(guò),這次就不再分析它了。
2.將View添加到decorview中的mContentParent中。
3.回調(diào)Activity的onContentChanged接口。
經(jīng)過(guò)以上操作,DecorView創(chuàng)建了,但還沒(méi)有正式添加到Window中。在ActivityResumeActivity中首先會(huì)調(diào)用Activity的onResume,再調(diào)用Activity的makeVisible,makeVisible中真正添加view ,代碼如下:
void makeVisible() {
if (!mWindowAdded) {
ViewManager wm = getWindowManager();
wm.addView(mDecor, getWindow().getAttributes());
mWindowAdded = true;
}
mDecor.setVisibility(View.VISIBLE);
}
通過(guò)上面的addView方法將View添加到Window。
三、Window操作View內(nèi)部機(jī)制
1.window的添加
一個(gè)window對(duì)應(yīng)一個(gè)view和一個(gè)viewRootImpl,window和view通過(guò)ViewRootImpl來(lái)建立聯(lián)系,它并不存在,實(shí)體是view。只能通過(guò) windowManager來(lái)操作它。
windowManager的實(shí)現(xiàn)類是windowManagerImpl。它并沒(méi)有直接實(shí)現(xiàn)三大操作,而是委托給WindowManagerGlobal。addView的實(shí)現(xiàn)分為以下幾步:
1).檢查參數(shù)是否合法。
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
if (display == null) {
throw new IllegalArgumentException("display must not be null");
}
if (!(params instanceof WindowManager.LayoutParams)) {
throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
}
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;
if (parentWindow != null) {
parentWindow.adjustLayoutParamsForSubWindow(wparams);
} else {
// If there's no parent and we're running on L or above (or in the
// system context), assume we want hardware acceleration.
final Context context = view.getContext();
if (context != null
&& context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
}
}
2).創(chuàng)建ViewRootImpl并將View添加到列表中。
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
3).通過(guò)ViewRootImpl來(lái)更新界面并完成window的添加過(guò)程 。
root.setView(view, wparams, panelParentView);
上面的root就是ViewRootImpl,setView中通過(guò)requestLayout()來(lái)完成異步刷新,看下requestLayout:
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
接下來(lái)通過(guò)WindowSession來(lái)完成window添加過(guò)程,WindowSession是一個(gè)Binder對(duì)象,真正的實(shí)現(xiàn)類是 Session,window的添加是一次IPC調(diào)用。
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets, mInputChannel);
} catch (RemoteException e) {
mAdded = false;
mView = null;
mAttachInfo.mRootView = null;
mInputChannel = null;
mFallbackEventHandler.setView(null);
unscheduleTraversals();
setAccessibilityFocus(null, null);
throw new RuntimeException("Adding window failed", e);
}
在Session內(nèi)部會(huì)通過(guò)WindowManagerService來(lái)實(shí)現(xiàn)Window的添加。
public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
int viewVisibility, int displayId, Rect outContentInsets, Rect outStableInsets,
InputChannel outInputChannel) {
return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId,
outContentInsets, outStableInsets, outInputChannel);
}
在WindowManagerService內(nèi)部會(huì)為每一個(gè)應(yīng)用保留一個(gè)單獨(dú)的session。
2.window的刪除
看下WindowManagerGlobal的removeView:
public void removeView(View view, boolean immediate) {
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
synchronized (mLock) {
int index = findViewLocked(view, true);
View curView = mRoots.get(index).getView();
removeViewLocked(index, immediate);
if (curView == view) {
return;
}
throw new IllegalStateException("Calling with view " + view
+ " but the ViewAncestor is attached to " + curView);
}
}
首先調(diào)用findViewLocked來(lái)查找刪除view的索引,這個(gè)過(guò)程就是建立數(shù)組遍歷。然后再調(diào)用removeViewLocked來(lái)做進(jìn)一步的刪除。
private void removeViewLocked(int index, boolean immediate) {
ViewRootImpl root = mRoots.get(index);
View view = root.getView();
if (view != null) {
InputMethodManager imm = InputMethodManager.getInstance();
if (imm != null) {
imm.windowDismissed(mViews.get(index).getWindowToken());
}
}
boolean deferred = root.die(immediate);
if (view != null) {
view.assignParent(null);
if (deferred) {
mDyingViews.add(view);
}
}
}
真正刪除操作是viewRootImpl來(lái)完成的。windowManager提供了兩種刪除接口,removeViewImmediate,removeView。它們分別表示異步刪除和同步刪除。具體的刪除操作由ViewRootImpl的die來(lái)完成。
boolean die(boolean immediate) {
// Make sure we do execute immediately if we are in the middle of a traversal or the damage
// done by dispatchDetachedFromWindow will cause havoc on return.
if (immediate && !mIsInTraversal) {
doDie();
return false;
}
if (!mIsDrawing) {
destroyHardwareRenderer();
} else {
Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
" window=" + this + ", title=" + mWindowAttributes.getTitle());
}
mHandler.sendEmptyMessage(MSG_DIE);
return true;
}
由上可知如果是removeViewImmediate,立即調(diào)用doDie,如果是removeView,用handler發(fā)送消息,ViewRootImpl中的Handler會(huì)處理消息并調(diào)用doDie。重點(diǎn)看下doDie:
void doDie() {
checkThread();
if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
synchronized (this) {
if (mRemoved) {
return;
}
mRemoved = true;
if (mAdded) {
dispatchDetachedFromWindow();
}
if (mAdded && !mFirst) {
destroyHardwareRenderer();
if (mView != null) {
int viewVisibility = mView.getVisibility();
boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
if (mWindowAttributesChanged || viewVisibilityChanged) {
// If layout params have been changed, first give them
// to the window manager to make sure it has the correct
// animation info.
try {
if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
& WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
mWindowSession.finishDrawing(mWindow);
}
} catch (RemoteException e) {
}
}
mSurface.release();
}
}
mAdded = false;
}
WindowManagerGlobal.getInstance().doRemoveView(this);
}
主要做四件事:
1.垃圾回收相關(guān)工作,比如清數(shù)據(jù),回調(diào)等。
2.通過(guò)Session的remove方法刪除Window,最終調(diào)用WindowManagerService的removeWindow
3.調(diào)用dispathDetachedFromWindow,在內(nèi)部會(huì)調(diào)用onDetachedFromWindow()和onDetachedFromWindowInternal()。當(dāng)view移除時(shí)會(huì)調(diào)用onDetachedFromWindow,它用于作一些資源回收。
4.通過(guò)doRemoveView刷新數(shù)據(jù),刪除相關(guān)數(shù)據(jù),如在mRoot,mDyingViews中刪除對(duì)象等。
void doRemoveView(ViewRootImpl root) {
synchronized (mLock) {
final int index = mRoots.indexOf(root);
if (index >= 0) {
mRoots.remove(index);
mParams.remove(index);
final View view = mViews.remove(index);
mDyingViews.remove(view);
}
}
if (HardwareRenderer.sTrimForeground && HardwareRenderer.isAvailable()) {
doTrimForeground();
}
}
3.更新window
看下WindowManagerGlobal中的updateViewLayout。
public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
if (!(params instanceof WindowManager.LayoutParams)) {
throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
}
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;
view.setLayoutParams(wparams);
synchronized (mLock) {
int index = findViewLocked(view, true);
ViewRootImpl root = mRoots.get(index);
mParams.remove(index);
mParams.add(index, wparams);
root.setLayoutParams(wparams, false);
}
}
通過(guò)viewRootImpl的setLayoutParams更新viewRootImpl的layoutParams,接著scheduleTraversals對(duì)view重新布局,包括測(cè)量,布局,重繪,此外它還會(huì)通過(guò)WindowSession來(lái)更新window。這個(gè)過(guò)程由WindowManagerService實(shí)現(xiàn)。這跟上面類似,就不再重復(fù),到此Window底層源碼就分析完啦。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
Android 多媒體播放API簡(jiǎn)單實(shí)例
這篇文章主要介紹了Android 多媒體播放API簡(jiǎn)單實(shí)例的相關(guān)資料,這里附有代碼實(shí)例及實(shí)現(xiàn)效果圖,需要的朋友可以參考下2016-12-12
Android Selector獲取焦點(diǎn)后文本背景修改的實(shí)現(xiàn)代碼
這篇文章主要介紹了Android Selector獲取焦點(diǎn)后文本背景修改的實(shí)現(xiàn)代碼,本文通過(guò)demo展示和實(shí)現(xiàn)代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-11-11
Flutter自定義實(shí)現(xiàn)神奇動(dòng)效的卡片切換視圖的示例代碼
這篇文章主要介紹了Flutter自定義實(shí)現(xiàn)神奇動(dòng)效的卡片切換視圖的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-04-04
IOS開(kāi)發(fā)向右滑動(dòng)返回前一個(gè)頁(yè)面功能(demo)
本文給大家介紹使用android實(shí)現(xiàn)向右滑動(dòng)返回一個(gè)頁(yè)面的功能,大家都知道在ios7中,蘋(píng)果的原生態(tài)應(yīng)用幾乎都能夠通過(guò)向右滑動(dòng)來(lái)返回到前一個(gè)頁(yè)面,這樣可以避免用戶在單手操作時(shí)用大拇指去點(diǎn)擊那個(gè)遙遠(yuǎn)的返回鍵,下面小編就給帶來(lái)了實(shí)現(xiàn)代碼,有需要的朋友可以參考下2016-06-06
六款值得推薦的android(安卓)開(kāi)源框架簡(jiǎn)介
同事整理的android(安卓)開(kāi)源框架,個(gè)個(gè)都堪稱經(jīng)典。32 個(gè)贊!2014-06-06
Android實(shí)現(xiàn)斷點(diǎn)續(xù)傳功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)斷點(diǎn)續(xù)傳功能,能在上次的斷點(diǎn)處繼續(xù)上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07
AndroidSDK Support自帶夜間、日間模式切換詳解
這篇文章主要為大家詳細(xì)介紹了AndroidSDK Support自帶夜間、日間模式切換,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09
Android實(shí)現(xiàn)小米相機(jī)底部滑動(dòng)指示器
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)小米相機(jī)底部滑動(dòng)指示器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04

