1. 程式人生 > >Activity、Window、View三者關係

Activity、Window、View三者關係

目錄介紹

  • 01.Window,View,子Window
  • 02.什麼是Activity
  • 03.什麼是Window
  • 04.什麼是DecorView
  • 05.什麼是View
  • 06.關係結構圖
  • 07.Window建立過程
  • 08.建立機制分析
    • 8.1 Activity例項的建立
    • 8.2 Activity中Window的建立
    • 8.3 DecorView的建立

彈窗系列部落格

  • 01.Activity、Window、View三者關係
    • 深入分析Activity、Window、View三者之間的關係
  • 02.Toast原始碼深度分析
    • 最簡單的建立,簡單改造避免重複建立,show()方法原始碼分析,scheduleTimeoutLocked吐司如何自動銷燬的,TN類中的訊息機制是如何執行的,普通應用的Toast顯示數量是有限制的,用程式碼解釋為何Activity銷燬後Toast仍會顯示,Toast偶爾報錯Unable to add window是如何產生的,Toast執行在子執行緒問題,Toast如何新增系統視窗的許可權等等
  • 03.DialogFragment原始碼分析
    • 最簡單的使用方法,onCreate(@Nullable Bundle savedInstanceState)原始碼分析,重點分析彈窗展示和銷燬原始碼,使用中show()方法遇到的IllegalStateException分析
  • 04.Dialog原始碼分析
    • AlertDialog原始碼分析,通過AlertDialog.Builder物件設定屬性,Dialog生命週期,Dialog中show方法展示彈窗分析,Dialog的dismiss銷燬彈窗,Dialog彈窗問題分析等等
  • 05.PopupWindow原始碼分析
    • 顯示PopupWindow,注意問題寬和高屬性,showAsDropDown()原始碼,dismiss()原始碼分析,PopupWindow和Dialog有什麼區別?為何彈窗點選一下就dismiss呢?
  • 06.Snackbar原始碼分析
    • 最簡單的建立,Snackbar的make方法原始碼分析,Snackbar的show顯示與點選消失原始碼分析,顯示和隱藏中動畫原始碼分析,Snackbar的設計思路,為什麼Snackbar總是顯示在最下面
  • 07.彈窗常見問題
    • DialogFragment使用中show()方法遇到的IllegalStateException,什麼常見產生的?Toast偶爾報錯Unable to add window,Toast執行在子執行緒導致崩潰如何解決?
  • 09.onAttachedToWindow和onDetachedFromWindow
    • onAttachedToWindow的呼叫過程,onDetachedFromWindow可以做什麼?
  • 10.DecorView介紹
    • 什麼是DecorView,DecorView的建立,DecorView的顯示,深度解析

01.Window,View,子Window

  • 彈窗有哪些型別
    • 使用子視窗:在 Android 程序內,我們可以直接使用型別為子視窗型別的視窗。在 Android 程式碼中的直接應用是 PopupWindow 或者是 Dialog 。這當然可以,不過這種視窗依賴於它的宿主視窗,它可用的條件是你的宿主視窗可用
    • 採用View系統:使用 View 系統去模擬一個視窗行為,且能更加快速的實現動畫效果,比如SnackBar 就是採用這套方案
    • 使用系統視窗:比如吐司Toast

02.什麼是Activity

  • Activity並不負責檢視控制,它只是控制生命週期和處理事件。真正控制檢視的是Window。一個Activity包含了一個Window,Window才是真正代表一個視窗。
  • Activity就像一個控制器,統籌檢視的新增與顯示,以及通過其他回撥方法,來與Window、以及View進行互動。

03.什麼是Window

  • Window是什麼?
    • 表示一個視窗的概念,是所有View的直接管理者,任何檢視都通過Window呈現(點選事件由Window->DecorView->View; Activity的setContentView底層通過Window完成)
    • Window是一個抽象類,具體實現是PhoneWindow。PhoneWindow中有個內部類DecorView,通過建立DecorView來載入Activity中設定的佈局R.layout.activity_main
    • 建立Window需要通過WindowManager建立,通過WindowManager將DecorView載入其中,並將DecorView交給ViewRoot,進行檢視繪製以及其他互動。
    • WindowManager是外界訪問Window的入口
    • Window具體實現位於WindowManagerService中
    • WindowManager和WindowManagerService的互動是通過IPC完成
  • 如何通過WindowManager新增Window(程式碼實現)?
    • 如下所示
      //1. 控制元件 
      Button button = new Button(this); 
      button.setText("Window Button"); 
      //2. 佈局引數 
      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.gravity = Gravity.LEFT | Gravity.TOP; 
      layoutParams.x = 100; 
      layoutParams.y = 300; 
      // 必須要有type不然會異常: the specified window type 0 is not valid 
      layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR; 
      //3. 獲取WindowManager並新增控制元件到Window中 
      WindowManager windowManager = getWindowManager(); 
      windowManager.addView(button, layoutParams);
      
  • WindowManager的主要功能是什麼?
    • 新增、更新、刪除View
      public interface ViewManager{ 
          public void addView(View view, ViewGroup.LayoutParams params); 
          //新增View 
          public void updateViewLayout(View view, ViewGroup.LayoutParams params); 
          //更新View 
          public void removeView(View view); 
          //刪除View 
      }
      

04.什麼是DecorView

  • DecorView是FrameLayout的子類,它可以被認為是Android檢視樹的根節點檢視。
    • DecorView作為頂級View,一般情況下它內部包含一個豎直方向的LinearLayout,在這個LinearLayout裡面有上下三個部分,上面是個ViewStub,延遲載入的檢視(應該是設定ActionBar,根據Theme設定),中間的是標題欄(根據Theme設定,有的佈局沒有),下面的是內容欄。
    • 具體情況和Android版本及主體有關,以其中一個佈局為例,如下所示:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:fitsSystemWindows="true"
        android:orientation="vertical">
        <!-- Popout bar for action modes -->
        <ViewStub
            android:id="@+id/action_mode_bar_stub"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inflatedId="@+id/action_mode_bar"
            android:layout="@layout/action_mode_bar"
            android:theme="?attr/actionBarTheme" />
    
        <FrameLayout
            style="?android:attr/windowTitleBackgroundStyle"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/windowTitleSize">
    
            <TextView
                android:id="@android:id/title"
                style="?android:attr/windowTitleStyle"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@null"
                android:fadingEdge="horizontal"
                android:gravity="center_vertical" />
        </FrameLayout>
    
        <FrameLayout
            android:id="@android:id/content"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:foreground="?android:attr/windowContentOverlay"
            android:foregroundGravity="fill_horizontal|top" />
    </LinearLayout>
    
  • 在Activity中通過setContentView所設定的佈局檔案其實就是被加到內容欄之中的,成為其唯一子View,就是上面的id為content的FrameLayout中,在程式碼中可以通過content來得到對應載入的佈局。
    ViewGroup content = (ViewGroup)findViewById(android.R.id.content);
    ViewGroup rootView = (ViewGroup) content.getChildAt(0);
    

06.關係結構圖

  • Activity 與 PhoneWindow 與 DecorView 關係圖
    • image

07.Window建立過程

  • App點選桌面圖片啟動過程
    • image
  • window啟動流程
    • image
  • Activity 與 PhoneWindow 與 DecorView 之間什麼關係?
    • 一個 Activity 對應一個 Window 也就是 PhoneWindow,一個 PhoneWindow 持有一個 DecorView 的例項,DecorView 本身是一個 FrameLayout。

08.建立機制分析

8.1 Activity例項的建立

  • ActivityThread中執行performLaunchActivity,從而生成了Activity的例項。原始碼如下所示,ActivityThread類中原始碼
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            ...
        } catch (Exception e) {
            ...
        }
    
        try {
            ...
            if (activity != 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);
                ...
            }
            ...
        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
            ...
        }
    
        return activity;
    }
    

8.2 Activity中Window的建立

  • 從上面的performLaunchActivity可以看出,在建立Activity例項的同時,會呼叫Activity的內部方法attach
  • 在attach該方法中完成window的初始化。原始碼如下所示,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,
            Window window, ActivityConfigCallback activityConfigCallback) {
    
        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);
        }
    }
    

8.3 DecorView的建立

  • 使用者執行Activity的setContentView方法,內部是呼叫PhoneWindow的setContentView方法,在PhoneWindow中完成DecorView的建立。流程
    • 1.Activity中的setContentView
    • 2.PhoneWindow中的setContentView
    • 3.PhoneWindow中的installDecor
    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }
    
    @Override
    public void setContentView(int layoutResID) {
        ...
        if (mContentParent == null) {
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }
        ...
    }
    
    private void installDecor() {
        if (mDecor == null) {
            mDecor = generateDecor();
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        }
        ...
    }
    

關於其他內容介紹

01.關於部落格彙總連結

02.關於我的部落格

GitHub連結:https://github.