Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android Window 的 9 問 9 答

編輯:Android 資訊

先前分享過一篇 Android View 繪製的 13 問 13 答,這篇文章則聚焦於 Android Window 的 9 個問題與解答。

1. 簡單說明 Window 是什麼?它在 Android 體系中扮演什麼角色?

答:Window 是一個抽象類,其實作類是 PhoneWindow。我們通常透過 WindowManager 來存取 Window,本質上是 WindowManager 與 WindowManagerService 之間的互動。

此外,Android 中所有你看得到的視圖——Activity、Dialog、Toast 等——都是附加在 Window 之上的。Window 就是 View 的直接管理者。

2. 如何使用 WindowManager 添加一個 View?

答:

Button bt = new Button(this); bt.setText("button here"); WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat.TRANSPARENT); layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; layoutParams.x = 300; layoutParams.y = 300; layoutParams.gravity = Gravity.RIGHT | Gravity.TOP; getWindowManager().addView(bt, layoutParams);

3. 總共有幾種 Window 類型?

答:三種。應用型 Window,即 Activity 這類;子 Window,即 Dialog 這類;系統型 Window,如 Toast、狀態欄等。

每種對應著不同的層級範圍:應用型 1–99、子型 1000–1999、系統型 2000–2999。層級數字越大,代表顯示在越頂層的 Window。

4. 使用系統 Window 需要注意什麼?

答:要留意 system_alert_window 這個權限,否則會出錯。

5. 嘗試簡單分析 Window 的添加過程?

答:即 window.addView() 函式的執行過程:

//首先我們要知道 windwmanger本身就是一個接口,他的實現是交給WindowManagerImpl 來做的。 public final class WindowManagerImpl implements WindowManager { //他的view方法 一看,發現也是基本沒做實際的addview操作 是交給mGlobal來做的 @Override public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) { applyDefaultToken(params); mGlobal.addView(view, params, mDisplay, mParentWindow); } //發現這是一個工廠嗎,到這裡一看就明白了,WindowManagerImpl的實際操作 都橋接給了WindowManagerGlobal來處理 private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance(); //先看一下WindowManagerGlobal的 重要變量,注意上面已經分析過了,WindowManagerGlobal本身自己是一個單例,全局唯一, //所以下面這些參數list ,全局也是唯一的,mViews 就是所有window對應的view,mRoots就是所有viewRootImpl,mParams就是這些 //view的參數,dyingviews 就是正在刪除的對象,就是那種你調用了remove操作 但是remove還沒有操作完畢的那些view private final ArrayList<View> mViews = new ArrayList<View>(); private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>(); private final ArrayList<WindowManager.LayoutParams> mParams = new ArrayList<WindowManager.LayoutParams>(); private final ArraySet<View> mDyingViews = new ArraySet<View>(); //所以 我們就看看WindowManagerGlobal源碼裡的addView是如何實現的 public void addView(View view, ViewGroup.LayoutParams params, Display display, Window parentWindow) { 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; //如果是子window 就調整一下參數 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; } } ViewRootImpl root; View panelParentView = null; synchronized (mLock) { // Start watching for system property changes. if (mSystemPropertyUpdater == null) { mSystemPropertyUpdater = new Runnable() { @Override public void run() { synchronized (mLock) { for (int i = mRoots.size() - 1; i >= 0; --i) { mRoots.get(i).loadSystemProperties(); } } } }; SystemProperties.addChangeCallback(mSystemPropertyUpdater); } int index = findViewLocked(view, false); if (index >= 0) { if (mDyingViews.contains(view)) { // Don't wait for MSG_DIE to make it's way through root's queue. mRoots.get(index).doDie(); } else { throw new IllegalStateException("View " + view + " has already been added to the window manager."); } // The previous removeView() had not completed executing. Now it has. } // If this is a panel window, then find the window it is being // attached to for future reference. if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW && wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) { final int count = mViews.size(); for (int i = 0; i < count; i++) { if (mRoots.get(i).mWindow.asBinder() == wparams.token) { panelParentView = mViews.get(i); } } } //這個代碼充分說明了每一個window都對應著一個view 和一個viewrootIMPL,window本身自己不存在, //他的意義就在於管理view,而管理view 就要通過windowmanager 最終走到windwmanagerglobal這裡來完成管理 root = new ViewRootImpl(view.getContext(), display); view.setLayoutParams(wparams); mViews.add(view); mRoots.add(root); mParams.add(wparams); } // do this last because it fires off messages to start doing things try { //view的最終繪制 是在viewrootimpl裡完成的,所以這裡view的繪制也是在這個裡面完成的 //我們在viewrootimpl裡能找到setview的源碼 他在這個函數裡調用了requetlayout root.setView(view, wparams, panelParentView); } catch (RuntimeException e) { // BadTokenException or InvalidDisplayException, clean up. synchronized (mLock) { final int index = findViewLocked(view, false); if (index >= 0) { removeViewLocked(index, true); } } throw e; } } //而requestLayout裡有scheduleTraversals方法 這個就是view繪制的入口處 public void requestLayout() { if (!mHandlingLayoutInLayoutRequest) { checkThread(); mLayoutRequested = true; scheduleTraversals(); } } //回到前面提到的setView那個函數 //我們可以看到requestLayout 結束以後 mWindowSession.addToDisplay 就有了這個方法的調用 //實際上這個方法 完成的就是一個window的添加。 requestLayout(); if ((mWindowAttributes.inputFeatures & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) { mInputChannel = new InputChannel(); } try { mOrigWindowType = mWindowAttributes.type; mAttachInfo.mRecomputeGlobalAttributes = true; collectViewAttributes(); res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes, getHostVisibility(), mDisplay.getDisplayId(), mAttachInfo.mContentInsets, mAttachInfo.mStableInsets, mInputChannel); //然後我們很容易就發現這是一個接口 並且代碼一看就知道 還是一個binder //所以實際上添加window的功能 就是通過BInder 是調用windwmangerservice的方法 來完成的 public interface IWindowSession extends android.os.IInterface { /** Local-side IPC implementation stub class. */ public static abstract class Stub extends android.os.Binder implements android.view.IWindowSession { private static final java.lang.String DESCRIPTOR = "android.view.IWindowSession"; /** Construct the stub at attach it to the interface. */ public Stub() { this.attachInterface(this, DESCRIPTOR); }

6. Activity 的 Window 是如何創建的?

答:應用型 Window 的創建過程如下:

//activity的window創建 由activityThread的performLaunchActivity 方法開始 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ...... if (activity != null) { Context appContext = createBaseContextForActivity(r, activity); CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); Configuration config = new Configuration(mCompatConfiguration); if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity " + r.activityInfo.name + " with config " + config); //其中最主要的就是attach方法 注意是調用的activity的attach方法 不是activitytherad的 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); ...... return activity; } 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) { attachBaseContext(context); mFragments.attachActivity(this, mContainer, null); //這裡一下就能看出來 Acitity的window對象 是由PolicyManager的makeNewWindow方法構造出來 //有興趣的還可以看一下 這裡set了很多接口 都是我們熟悉的那些方法 mWindow = PolicyManager.makeNewWindow(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; } //makenewWindow就是在這裡被調用的,可以看出來 makenewWindow返回的 正是phoneWindow對象 //到這裡我們的window對象就生成了, public class Policy implements IPolicy { private static final String TAG = "PhonePolicy"; private static final String[] preload_classes = { "com.android.internal.policy.impl.PhoneLayoutInflater", "com.android.internal.policy.impl.PhoneWindow", "com.android.internal.policy.impl.PhoneWindow$1", "com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback", "com.android.internal.policy.impl.PhoneWindow$DecorView", "com.android.internal.policy.impl.PhoneWindow$PanelFeatureState", "com.android.internal.policy.impl.PhoneWindow$PanelFeatureState$SavedState", }; static { // For performance reasons, preload some policy specific classes when // the policy gets loaded. for (String s : preload_classes) { try { Class.forName(s); } catch (ClassNotFoundException ex) { Log.e(TAG, "Could not preload class for phone policy: " + s); } } } public Window makeNewWindow(Context context) { return new PhoneWindow(context); } public LayoutInflater makeNewLayoutInflater(Context context) { return new PhoneLayoutInflater(context); } public WindowManagerPolicy makeNewWindowManager() { return new PhoneWindowManager(); } public FallbackEventHandler makeNewFallbackEventHandler(Context context) { return new PhoneFallbackEventHandler(context); } } //再看activity的方法 就是在這裡把我們的布局文件和window給關聯了起來 //我們上面已經知道window對象就是phonewindow 所以這裡就要看看phonewindow的setContentView方法 public void setContentView(@LayoutRes int layoutResID) { getWindow().setContentView(layoutResID); initWindowDecorActionBar(); } //phoneWindow的setContentView方法 //要注意的是 這個方法執行完畢 我們也只是 通過decorView創建好了 我們自己的view對象而已。 //但是這個對象還沒有被顯示出來,只是存在於內存之中。decorview真正被顯示 要在makevisible方法裡了 @Override 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) { //這個就是創建decorview的 decorView就是那個framelayout我們的根布局 有一個標題欄和內容欄 //其中內容蘭 就是android.R.id.content 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 { //這裡就是我們自己寫的布局 layout 給關聯到deorview的content布局裡面 mLayoutInflater.inflate(layoutResID, mContentParent); } final Callback cb = getCallback(); if (cb != null && !isDestroyed()) { //添加完畢以後調用回調 cb.onContentChanged(); } }

7. Dialog 的 Window 創建過程?

答:子 Window 的創建過程如下。其實和 Activity 差不多,差別在於 Activity 對 decorView 的顯示是自動的,交給 ActivityThread 依流程處理,最後由 makeVisible 完成顯示;而 Dialog 則需要你手動呼叫 show 方法來完成這個過程。

//看Dialog的構造函數 ,和acitivity差不多 也是PhoneWindow 對象。 Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) { if (createContextThemeWrapper) { if (themeResId == 0) { final TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(R.attr.dialogTheme, outValue, true); themeResId = outValue.resourceId; } mContext = new ContextThemeWrapper(context, themeResId); } else { mContext = context; } mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); final Window w = new PhoneWindow(mContext); mWindow = w; w.setCallback(this); w.setOnWindowDismissedCallback(this); w.setWindowManager(mWindowManager, null, null); w.setGravity(Gravity.CENTER); mListenersHandler = new ListenersHandler(this); } //Dialog的setContentView方法 也是調用的phonewindow的方法 和acitivity流程也是一樣的 public void setContentView(@LayoutRes int layoutResID) { mWindow.setContentView(layoutResID); } //我們都知道dialog必須要show才能顯示出來, public void show() { if (mShowing) { if (mDecor != null) { if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) { mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR); } mDecor.setVisibility(View.VISIBLE); } return; } mCanceled = false; if (!mCreated) { dispatchOnCreate(null); } onStart(); mDecor = mWindow.getDecorView(); if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) { final ApplicationInfo info = mContext.getApplicationInfo(); mWindow.setDefaultIcon(info.icon); mWindow.setDefaultLogo(info.logo); mActionBar = new WindowDecorActionBar(this); } WindowManager.LayoutParams l = mWindow.getAttributes(); if ((l.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) { WindowManager.LayoutParams nl = new WindowManager.LayoutParams(); nl.copyFrom(l); nl.softInputMode |= WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; l = nl; } try { //在這裡 把decorview給add到這個window中了 與activity流程也是一樣的 mWindowManager.addView(mDecor, l); mShowing = true; sendShowMessage(); } finally { } }

8. Dialog 的創建是否必須要有 Activity 的引用?

答:不需要,只要把它改為系統型 Window 即可。系統型 Window 不需要 Activity 作為引用,注意別遺漏了權限。

Dialog dialog=new Dialog(MainActivity.this.getApplicationContext()); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); TextView textView=new TextView(MainActivity.this); textView.setText("this is dialog not use activity this"); dialog.setContentView(textView); dialog.show();

9. Toast 的 Window 創建過程?

答:這屬於系統級別的 Window 創建,和前面兩種略有不同,核心其實就是 NotificationManagerService 與 Toast 本身之間的相互呼叫,本質上是一個簡單的 IPC 過程。前面 Binder 的教學已談過如何利用 Binder 進行雙向通訊,而 Toast 的源碼正是利用 Binder 的雙向通訊來完成功能。源碼這裡就不再贅述,有興趣的讀者可以自行研究。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved