从源码入手理解Window和WindowManager

来源:互联网 发布:mac制作win7安装盘教程 编辑:程序博客网 时间:2024/04/26 12:05

一、Window简介


(1)Window表示一个窗口的概念,一般用不到,当在某些特殊的时候我们需要在桌面上显示一个类似悬浮窗的东西就需要Window来实现。
(2)Window是一个抽象类,它的具体实现是PhoneWindow。
(3)创建一个Window只需要通过WindowManager即可完成。
(4)WindowManager是外界访问Window的入口,Window的具体实现是WindowManagerService,WindowManager和WindowManagerService的交互是一个IPC过程。
(5)Android中所有的视图都是通过Window呈现的,不管是Activity、Dialog还是Toast,他们的视图实际上都是附加在Window上的,因此Window实际是View的直接管理者。


二、Window和WindowManager


1、使用WindowManager添加一个Window


为了分析Window的工作机制,我们需要先了解如何使用WindowManager添加一个Window:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.              * 下面的代码演示了通过WindowManager添加Window的过程: 
  3.              * (1)创建Button按钮。 
  4.              * (2)为Button设置文字内容。 
  5.              * (3)创建一个WindowManager.LayoutParams的参数,设置Button的宽高之类的。 
  6.              * (4)为WindowManager.LayoutParams设置Flags参数。 
  7.              * (5)为WindowManager.LayoutParams设置type参数。 
  8.              * (6、7、8)为WindowManager.LayoutParams设置中心点、坐标位置。 
  9.              * (9)给Button设置触摸事件。 
  10.              * (10)将Button按照WindowManager.LayoutParams参数用WindowManager添加View即可。 
  11.              * */  
  12.             mFloatingButton = new Button(this);  
  13.             mFloatingButton.setText("click me");  
  14.             mLayoutParams = new WindowManager.LayoutParams(  
  15.                     LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 00,  
  16.                     PixelFormat.TRANSPARENT);  
  17.             mLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL  
  18.                     | LayoutParams.FLAG_NOT_FOCUSABLE  
  19.                     | LayoutParams.FLAG_SHOW_WHEN_LOCKED;  
  20.             mLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR;  
  21.             mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;  
  22.             mLayoutParams.x = 100;  
  23.             mLayoutParams.y = 300;  
  24.             mFloatingButton.setOnTouchListener(this);  
  25.             mWindowManager.addView(mFloatingButton, mLayoutParams);  
(1)Flags参数表示Window的属性,它有很多选项,通过这些选项可以控制Window的显示特性,下面介绍几个主要的:
FLAG_NOT_FOCUSABLE:表示Window不需要获取焦点,也不需要接收各种输入事件,此标记会同时启用FLAG_NOT_TOUCH_MODAL,最终事件会直接传递给下层的具有焦点的Window。
FLAG_NOT_TOUCH_MODAL:在此模式下,系统会将当前Window区域以外的单击事件传递给底层的Window,当前Window区域以内的单击事件则自己处理。 一般来说都需要开启此标记,否则其他Window将无法收到单击事件。
 FLAG_SHOW_WHEN_LOCKED:此模式可以让Window显示在锁屏的界面上。
(2)Type参数表示Window的类型,一共有三种类型:
应用Window(层级范围1~99):对应着一个Activity。
子Window(层级范围1000~1999):不能单独存在,它需要附属在特定的父Window之中,比如常见的Dialog就是一个子Window。
系统Window(层级范围2000~2999):是需要声明权限才能创建的Window,比如Toast和系统状态栏都属于系统Window。
 层级范围对应这WindowManager.LayoutParams的type参数,层级大的会覆盖在层级小的Window上面。所以系统层级是最大的,系统层级一般选用TYPE_SYSTEM_ERROR或者TYPE_SYSTEM_OVERLAY。 还有哦,系统层级需要声明权限:不然会报错:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />  
(3)将Button按照WindowManager.LayoutParams参数用WindowManager添加View即可。 所以这个Button就作为一个新的Window了。
 !!!!!Window并不是实际存在的,它以View的形式存在。!!!!!!
WindowManager所提供的功能很简单,常用的只有三个方法:即添加View、更新View和删除View。这三个方法定义在ViewManager中,ViewManager是一个接口,而WindowManager正是继承了ViewManager。
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package android.view;  
  2.   
  3. /** Interface to let you add and remove child views to an Activity. To get an instance 
  4.   * of this class, call {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}. 
  5.   */  
  6. public interface ViewManager  
  7. {  
  8.     /** 
  9.      * Assign the passed LayoutParams to the passed View and add the view to the window. 
  10.      * <p>Throws {@link android.view.WindowManager.BadTokenException} for certain programming 
  11.      * errors, such as adding a second view to a window without removing the first view. 
  12.      * <p>Throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a 
  13.      * secondary {@link Display} and the specified display can't be found 
  14.      * (see {@link android.app.Presentation}). 
  15.      * @param view The view to be added to this window. 
  16.      * @param params The LayoutParams to assign to view. 
  17.      */  
  18.     public void addView(View view, ViewGroup.LayoutParams params);  
  19.     public void updateViewLayout(View view, ViewGroup.LayoutParams params);  
  20.     public void removeView(View view);  
  21. }  
 * (1)ViewManager这个接口是由WindowManager来继承的,WindowManager可以用来创建Window。
 * ViewManager这里面提供了三个方法,分别是添加、更新和删除View。
 * (2)WindowManagerImpl继承自WindowManager,
 * 而WindowManager又是继承自ViewManager,
 * addView、updateViewLayout、removeView都是来自ViewManager的。
 * 所以在WindowManagerImpl具体实现了这三个方法。

继承关系:
ViewManager  -->> WindowManager(继承自ViewManager) -->> WindowManagerImpl(继承自WindowManager) -->> WindowManagerGlobal(WindowManagerImpl内部的一个对象) 
在ViewManager中有三个方法:addView、updateViewLayout、removeView。它们最终是在WindowManagerGlobal中具体实现的。

2、下面这个例子中的onTouch实现了拖动的Window效果

[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package com.ryg.chapter_8;  
  2.   
  3. import com.ryg.chapter_8.R;  
  4.   
  5. import android.annotation.SuppressLint;  
  6. import android.app.Activity;  
  7. import android.content.Context;  
  8. import android.graphics.PixelFormat;  
  9. import android.os.Bundle;  
  10. import android.view.Gravity;  
  11. import android.view.MotionEvent;  
  12. import android.view.View;  
  13. import android.view.View.OnTouchListener;  
  14. import android.view.WindowManager;  
  15. import android.view.WindowManager.LayoutParams;  
  16. import android.widget.Button;  
  17.   
  18. public class TestActivity extends Activity implements OnTouchListener {  
  19.   
  20.     private static final String TAG = "TestActivity";  
  21.   
  22.     private Button mCreateWindowButton;  
  23.   
  24.     private Button mFloatingButton;  
  25.     private WindowManager.LayoutParams mLayoutParams;  
  26.     private WindowManager mWindowManager;  
  27.   
  28.     @Override  
  29.     protected void onCreate(Bundle savedInstanceState) {  
  30.         super.onCreate(savedInstanceState);  
  31.         setContentView(R.layout.activity_test);  
  32.         initView();  
  33.     }  
  34.   
  35.     private void initView() {  
  36.         mCreateWindowButton = (Button) findViewById(R.id.button1);  
  37.         mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);  
  38.     }  
  39.   
  40.     public void onButtonClick(View v) {  
  41.         if (v == mCreateWindowButton) {  
  42.             /* 
  43.              * 下面的代码演示了通过WindowManager添加Window的过程: 
  44.              * */  
  45.             mFloatingButton = new Button(this);  
  46.             mFloatingButton.setText("click me");  
  47.             mLayoutParams = new WindowManager.LayoutParams(  
  48.                     LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 00,  
  49.                     PixelFormat.TRANSPARENT);  
  50.             mLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL  
  51.                     | LayoutParams.FLAG_NOT_FOCUSABLE  
  52.                     | LayoutParams.FLAG_SHOW_WHEN_LOCKED;  
  53.             mLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR;  
  54.             mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;  
  55.             mLayoutParams.x = 100;  
  56.             mLayoutParams.y = 300;  
  57.             mFloatingButton.setOnTouchListener(this);  
  58.             mWindowManager.addView(mFloatingButton, mLayoutParams);  
  59.         }  
  60.     }  
  61.   
  62.     @SuppressLint("ClickableViewAccessibility"@Override  
  63.     public boolean onTouch(View v, MotionEvent event) {  
  64.         int rawX = (int) event.getRawX();  
  65.         int rawY = (int) event.getRawY();  
  66.         switch (event.getAction()) {  
  67.         case MotionEvent.ACTION_DOWN: {  
  68.             break;  
  69.         }  
  70.         case MotionEvent.ACTION_MOVE: {  
  71.             /* 
  72.              * 如果想要实现可以拖动的Window效果, 
  73.              * 只需要根据手指的位置来设定LayoutParams中的x和y的值即可改变Window的位置。 
  74.              * */  
  75.             int x = (int) event.getX();  
  76.             int y = (int) event.getY();  
  77.             mLayoutParams.x = rawX;  
  78.             mLayoutParams.y = rawY;  
  79.             mWindowManager.updateViewLayout(mFloatingButton, mLayoutParams);  
  80.             break;  
  81.         }  
  82.         case MotionEvent.ACTION_UP: {  
  83.             break;  
  84.         }  
  85.         default:  
  86.             break;  
  87.         }  
  88.   
  89.         return false;  
  90.     }  
  91.   
  92.     @Override  
  93.     protected void onDestroy() {  
  94.         try {  
  95.             mWindowManager.removeView(mFloatingButton);  
  96.         } catch (IllegalArgumentException e) {  
  97.             e.printStackTrace();  
  98.         }  
  99.         super.onDestroy();  
  100.     }  
  101. }  



三、Window的内部机制


1、综述


Window是一个抽象概念,每一个Window都对应着一个View和一个ViewRootImpl,Window和View通过ViewRootImpl来建立联系,因此Window并不是实际存在的,它是以View的形式存在。这点从WindowManager的定义也可以看出,它提供的三个接口方法addView、updateViewLayout、removeView都是针对View的,这说明View才是WindowManager存在的实体。在实际使用中无法直接访问Window,对Window的访问必须通过WindowManager。

ViewManager  -->> WindowManager(继承自ViewManager) -->> WindowManagerImpl(继承自WindowManager) -->>WindowManagerGlobal(WindowManagerImpl内部的一个对象) -->> ViewRooImpl

2、Window的添加过程


(1)可以发现WindowManagerImpl并没有实现WindowManager的三大操作,而是全部交给WindowManagerGlobal来处理,WindowManagerGlobal以工厂的形式向外提供自己的实例。就是说WindowManagerImpl将所有的操作全部委托给WindowManagerGlobal来实现。这是一种桥接模式。
(2)WindowManagerImpl.java文件:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. package android.view;  
  2.   
  3. /** 
  4.  * Provides low-level communication with the system window manager for 
  5.  * operations that are bound to a particular context, display or parent window. 
  6.  * Instances of this object are sensitive to the compatibility info associated 
  7.  * with the running application. 
  8.  * 
  9.  * This object implements the {@link ViewManager} interface, 
  10.  * allowing you to add any View subclass as a top-level window on the screen. 
  11.  * Additional window manager specific layout parameters are defined for 
  12.  * control over how windows are displayed.  It also implements the {@link WindowManager} 
  13.  * interface, allowing you to control the displays attached to the device. 
  14.  *  
  15.  * <p>Applications will not normally use WindowManager directly, instead relying 
  16.  * on the higher-level facilities in {@link android.app.Activity} and 
  17.  * {@link android.app.Dialog}. 
  18.  *  
  19.  * <p>Even for low-level window manager access, it is almost never correct to use 
  20.  * this class.  For example, {@link android.app.Activity#getWindowManager} 
  21.  * provides a window manager for adding windows that are associated with that 
  22.  * activity -- the window manager will not normally allow you to add arbitrary 
  23.  * windows that are not associated with an activity. 
  24.  * 
  25.  * @see WindowManager 
  26.  * @see WindowManagerGlobal 
  27.  * @hide 
  28.  */  
  29. public final class WindowManagerImpl implements WindowManager {  
  30.     private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();  
  31.     private final Display mDisplay;  
  32.     private final Window mParentWindow;  
  33.   
  34.     public WindowManagerImpl(Display display) {  
  35.         this(display, null);  
  36.     }  
  37.   
  38.     private WindowManagerImpl(Display display, Window parentWindow) {  
  39.         mDisplay = display;  
  40.         mParentWindow = parentWindow;  
  41.     }  
  42.   
  43.     public WindowManagerImpl createLocalWindowManager(Window parentWindow) {  
  44.         return new WindowManagerImpl(mDisplay, parentWindow);  
  45.     }  
  46.   
  47.     public WindowManagerImpl createPresentationWindowManager(Display display) {  
  48.         return new WindowManagerImpl(display, mParentWindow);  
  49.     }  
  50.   
  51.     /* 
  52.      * Window的添加,即View的添加: 
  53.      * */  
  54.     @Override  
  55.     public void addView(View view, ViewGroup.LayoutParams params) {  
  56.         /* 
  57.          * 这里变成了四个参数: 
  58.          * */   
  59.         mGlobal.addView(view, params, mDisplay, mParentWindow);  
  60.     }  
  61.   
  62.     @Override  
  63.     public void updateViewLayout(View view, ViewGroup.LayoutParams params) {  
  64.         mGlobal.updateViewLayout(view, params);  
  65.     }  
  66.   
  67.     /* 
  68.      * Window的删除,即View的删除: 
  69.      * */  
  70.     @Override  
  71.     public void removeView(View view) {  
  72.         mGlobal.removeView(view, false);  
  73.     }  
  74.   
  75.     @Override  
  76.     public void removeViewImmediate(View view) {  
  77.         mGlobal.removeView(view, true);  
  78.     }  
  79.   
  80.     @Override  
  81.     public Display getDefaultDisplay() {  
  82.         return mDisplay;  
  83.     }  
  84. }  
(3)WindowManagerGlobal.java文件中的addView方法首先检查参数是否合法,如果是子Window那么还需要调整一些布局参数:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. if (view == null) {  
  2.             throw new IllegalArgumentException("view must not be null");  
  3.         }  
  4.         if (display == null) {  
  5.             throw new IllegalArgumentException("display must not be null");  
  6.         }  
  7.         if (!(params instanceof WindowManager.LayoutParams)) {  
  8.             throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");  
  9.         }  
  10.   
  11.         /* 
  12.          * 如果是子Window,那么还需要调整一些布局参数: 
  13.          * */  
  14.         final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;  
  15.         if (parentWindow != null) {  
  16.             parentWindow.adjustLayoutParamsForSubWindow(wparams);  
  17.         }  
(4)在WindowManagerGlobal内部有如下几个列表比较重要:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. // 存储Window对应的所有View:  
  2. private final ArrayList<View> mViews = new ArrayList<View>();  
  3. // 存储Window对应的所有ViewRootImpl:  
  4. private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();  
  5. // 存储Window对应的所有的布局参数:  
  6. private final ArrayList<WindowManager.LayoutParams> mParams =  
  7.         new ArrayList<WindowManager.LayoutParams>();  
  8. // 存储正在被删除的View对象,或者说是那些已经调用removeView方法但是删除操作还未完成的Window对象:  
  9. private final ArraySet<View> mDyingViews = new ArraySet<View>();  
在WindowManagerGlobal.java文件中的addView方法中通过如下方式将Window的一系列对象添加到列表中:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. root = new ViewRootImpl(view.getContext(), display);  
  2.   
  3. view.setLayoutParams(wparams);  
  4.   
  5. mViews.add(view);  
  6. mRoots.add(root);  
  7. mParams.add(wparams);  
(5)WindowManagerGlobal.java文件中的addView方法中通过ViewRootImpl来更新界面并完成Window的添加过程:这一步骤由ViewRootImpl的setView方法来完成。
在ViewRootImpl的setView方法中又会调用requestLayout方法来完成异步刷新请求。
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * setView方法的内部会通过requestLayout方法来完成异步刷新请求。 
  3.  * */  
  4. @Override  
  5. public void requestLayout() {  
  6.     if (!mHandlingLayoutInLayoutRequest) {  
  7.         checkThread();  
  8.         mLayoutRequested = true;  
  9.         /* 
  10.          * 这里实际才是View绘制的入口: 
  11.          * */  
  12.         scheduleTraversals();  
  13.     }  
  14. }  
在ViewRootImpl的setView方法中调用requestLayout方法后会接着通过WindowSession最终来完成Window的添加过程。
下面的mWindowSession的类型是IWindowSession,它是一个Binder对象,真正的实现类是Session,也就是Window的添加过程试一次IPC调用。在Session的内部会通过WindowManagerService来实现Window的添加: mWindowSession.addToDisplay。如此一来,Window的添加请求就交给WindowManagerService去处理了, 在WindowManagerService内部会为每一个应用保留一个单独的Session。具体的WindowManagerService的内部实现,我们就不讲了,深入进去没有太大的意义, 可以自行查看。
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. try {  
  2.     mOrigWindowType = mWindowAttributes.type;  
  3.     mAttachInfo.mRecomputeGlobalAttributes = true;  
  4.     collectViewAttributes();  
  5.     res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,  
  6.             getHostVisibility(), mDisplay.getDisplayId(),  
  7.             mAttachInfo.mContentInsets, mInputChannel);  
  8. catch (RemoteException e) {  
  9.     mAdded = false;  
  10.     mView = null;  
  11.     mAttachInfo.mRootView = null;  
  12.     mInputChannel = null;  
  13.     mFallbackEventHandler.setView(null);  
  14.     unscheduleTraversals();  
  15.     setAccessibilityFocus(nullnull);  
  16.     throw new RuntimeException("Adding window failed", e);  
  17. }  
在Session内部会通过WindowManagerService来实现Window的添加:
略。
如此一来,Window的添加请求就交给WindowManagerService去处理了,在WindowManagerService内部会为每一个应用保留一个单独的Session。具体Window在WindowManagerService内部是如何添加的我们并不研究。

(6)下面给出WindowManagerGlobal.java文件中的addView方法的完整代码:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public void addView(View view, ViewGroup.LayoutParams params,  
  2.         Display display, Window parentWindow) {  
  3.     /* 
  4.      * 第一步:下面的四个if语句都是在检查参数是否合法: 
  5.      * */  
  6.     if (view == null) {  
  7.         throw new IllegalArgumentException("view must not be null");  
  8.     }  
  9.     if (display == null) {  
  10.         throw new IllegalArgumentException("display must not be null");  
  11.     }  
  12.     if (!(params instanceof WindowManager.LayoutParams)) {  
  13.         throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");  
  14.     }  
  15.   
  16.     /* 
  17.      * 如果是子Window,那么还需要调整一些布局参数: 
  18.      * */  
  19.     final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;  
  20.     if (parentWindow != null) {  
  21.         parentWindow.adjustLayoutParamsForSubWindow(wparams);  
  22.     }  
  23.   
  24.     ViewRootImpl root;  
  25.     View panelParentView = null;  
  26.   
  27.     synchronized (mLock) {  
  28.         // Start watching for system property changes.  
  29.         if (mSystemPropertyUpdater == null) {  
  30.             mSystemPropertyUpdater = new Runnable() {  
  31.                 @Override public void run() {  
  32.                     synchronized (mLock) {  
  33.                         for (int i = mRoots.size() - 1; i >= 0; --i) {  
  34.                             mRoots.get(i).loadSystemProperties();  
  35.                         }  
  36.                     }  
  37.                 }  
  38.             };  
  39.             SystemProperties.addChangeCallback(mSystemPropertyUpdater);  
  40.         }  
  41.   
  42.         int index = findViewLocked(view, false);  
  43.         if (index >= 0) {  
  44.             if (mDyingViews.contains(view)) {  
  45.                 // Don't wait for MSG_DIE to make it's way through root's queue.  
  46.                 mRoots.get(index).doDie();  
  47.             } else {  
  48.                 throw new IllegalStateException("View " + view  
  49.                         + " has already been added to the window manager.");  
  50.             }  
  51.             // The previous removeView() had not completed executing. Now it has.  
  52.         }  
  53.   
  54.         // If this is a panel window, then find the window it is being  
  55.         // attached to for future reference.  
  56.         if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&  
  57.                 wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {  
  58.             final int count = mViews.size();  
  59.             for (int i = 0; i < count; i++) {  
  60.                 if (mRoots.get(i).mWindow.asBinder() == wparams.token) {  
  61.                     panelParentView = mViews.get(i);  
  62.                 }  
  63.             }  
  64.         }  
  65.   
  66.         /* 
  67.          * WindowManagerGlobal内部有一些比较重要的列表,这些列表上面有声明过, 
  68.          * 下面的几条语句将Window的一系列对象添加到这些列表中, 
  69.          * */  
  70.         root = new ViewRootImpl(view.getContext(), display);  
  71.   
  72.         view.setLayoutParams(wparams);  
  73.   
  74.         mViews.add(view);  
  75.         mRoots.add(root);  
  76.         mParams.add(wparams);  
  77.     }  
  78.   
  79.     // do this last because it fires off messages to start doing things  
  80.     try {  
  81.         /* 
  82.          * 通过ViewRootImpl来更新界面并完成Window的添加过程。 
  83.          * 这个root就是ViewRootImpl类对象。 
  84.          * View的绘制过程就是由ViewRootImpl来完成的。 
  85.          * setView内部会通过requestLayout来完成异步刷新请求。 
  86.          * */  
  87.         root.setView(view, wparams, panelParentView);  
  88.     } catch (RuntimeException e) {  
  89.         // BadTokenException or InvalidDisplayException, clean up.  
  90.         synchronized (mLock) {  
  91.             final int index = findViewLocked(view, false);  
  92.             if (index >= 0) {  
  93.                 removeViewLocked(index, true);  
  94.             }  
  95.         }  
  96.         throw e;  
  97.     }  
  98. }  

(7)整体的调用关系是:

ViewManager  -->> WindowManager(继承自ViewManager) -->> WindowManagerImpl(继承自WindowManager) -->>WindowManagerGlobal(WindowManagerImpl内部的一个对象) -->> ViewRooImpl.setView(ViewRooImpl是WindowManagerGlobal的addView方法中的一个对象) -->> requestLayout(setView中的一个方法调用) -->> WindowSession(在setView方法中,它是一个Binder对象,用于与WindowManagerService进行IPC通信) -->> Session(WindowSession的具体实现) -->> WindowManagerService(实现Window的添加)


3、Window的删除过程


(1)Window的删除过程和添加过程一样,都是先通过WindowManagerImpl后,再进一步通过WindowManagerGlobal来实现的。
(2)WindowManagerGlobal.java中的removeView方法:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /*** 
  2.  * WindowManager的removeView的最终源头: 
  3.  * @param view 
  4.  * @param immediate 
  5.  */  
  6. public void removeView(View view, boolean immediate) {  
  7.     if (view == null) {  
  8.         throw new IllegalArgumentException("view must not be null");  
  9.     }  
  10.   
  11.     synchronized (mLock) {  
  12.     // 首先查找待删除的View的索引,查找过程就是遍历建立的数组:  
  13.         int index = findViewLocked(view, true);  
  14.         View curView = mRoots.get(index).getView();  
  15.         // 然后调用这个方法进一步删除:  
  16.         removeViewLocked(index, immediate);  
  17.         if (curView == view) {  
  18.             return;  
  19.         }  
  20.   
  21.         throw new IllegalStateException("Calling with view " + view  
  22.                 + " but the ViewAncestor is attached to " + curView);  
  23.     }  
  24. }  
(3)removeViewLocked是通过ViewRootImpl来完成删除操作的。在WindowManager中提供了两种删除接口removeView和removeViewImmediate,它们分别表示异步删除和同步删除,其中removeViewImmediate使用起来需要特别注意,一般来说不需要使用此方法来删除Window以免发生意外的错误。具体的删除操作由ViewRootImpl的die方法来完成。在die的内部会判断是异步删除还是同步删除。在异步删除的情况下,die方法只是发送了一个请求删除的消息后就立刻返回了,这个时候View并没有完成删除操作,所以最后会将其添加到mDyingViews中,mDyingViews表示待删除的View列表。
WindowManagerGlobal.java中的removeViewLocked方法:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * 根据待删除View的index来做进一步删除View, 
  3.  * removeViewLocked是通过ViewRootImpl来完成删除操作的。 
  4.  * */  
  5. private void removeViewLocked(int index, boolean immediate) {  
  6.     ViewRootImpl root = mRoots.get(index);  
  7.     View view = root.getView();  
  8.   
  9.     if (view != null) {  
  10.         InputMethodManager imm = InputMethodManager.getInstance();  
  11.         if (imm != null) {  
  12.             imm.windowDismissed(mViews.get(index).getWindowToken());  
  13.         }  
  14.     }  
  15.   
  16.     boolean deferred = root.die(immediate);  
  17.     if (view != null) {  
  18.         view.assignParent(null);  
  19.         if (deferred) {  
  20.             mDyingViews.add(view);  
  21.         }  
  22.     }  
  23. }  
(4)具体的删除操作由ViewRootImpl的die方法来完成。 在die的内部会判断是异步删除还是同步删除。在异步删除的情况下,die方法只是发送了一个请求删除的消息后就立刻返回了,这个时候View并没有完成删除操作。doDie内部会调用dispatchDetachedFromWindow方法,真正删除View的逻辑在dispatchDetachedFromWindow方法的内部实现。
ViewRootImpl.java中die方法:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. boolean die(boolean immediate) {  
  2.     // Make sure we do execute immediately if we are in the middle of a traversal or the damage  
  3.     // done by dispatchDetachedFromWindow will cause havoc on return.  
  4.     /* 
  5.      * 如果是同步删除(立即删除),那么就不发送消息直接调用doDie方法。 
  6.      * */  
  7.     if (immediate && !mIsInTraversal) {  
  8.         doDie();  
  9.         return false;  
  10.     }  
  11.   
  12.     if (!mIsDrawing) {  
  13.         destroyHardwareRenderer();  
  14.     } else {  
  15.         Log.e(TAG, "Attempting to destroy the window while drawing!\n" +  
  16.                 "  window=" + this + ", title=" + mWindowAttributes.getTitle());  
  17.     }  
  18.     /* 
  19.      * 如果是异步操作,那么就发送一个MSG_DIE的消息, 
  20.      * ViewRootImpl中的Handler会处理此消息并调用doDie方法。 
  21.      * */  
  22.     mHandler.sendEmptyMessage(MSG_DIE);  
  23.     return true;  
  24. }  
(5)ViewRootImpl.java中doDie方法:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * 在Die方法中会判断是用异步删除还是同步删除, 
  3.  * 但归根结底还是要用doDie来完成删除View的操作。 
  4.  * 在doDie的内部会调用dispatchDetachedFromWindow方法, 
  5.  * 真正删除View的逻辑在dispatchDetachedFromWindow方法的内部实现。 
  6.  * */  
  7. void doDie() {  
  8.     checkThread();  
  9.     if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);  
  10.     synchronized (this) {  
  11.         if (mRemoved) {  
  12.             return;  
  13.         }  
  14.         mRemoved = true;  
  15.         if (mAdded) {  
  16.             /* 
  17.              * 这儿才是重点呢: 
  18.              * */  
  19.             dispatchDetachedFromWindow();  
  20.         }  
  21.   
  22.         if (mAdded && !mFirst) {  
  23.             invalidateDisplayLists();  
  24.             destroyHardwareRenderer();  
  25.   
  26.             if (mView != null) {  
  27.                 int viewVisibility = mView.getVisibility();  
  28.                 boolean viewVisibilityChanged = mViewVisibility != viewVisibility;  
  29.                 if (mWindowAttributesChanged || viewVisibilityChanged) {  
  30.                     // If layout params have been changed, first give them  
  31.                     // to the window manager to make sure it has the correct  
  32.                     // animation info.  
  33.                     try {  
  34.                         if ((relayoutWindow(mWindowAttributes, viewVisibility, false)  
  35.                                 & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {  
  36.                             mWindowSession.finishDrawing(mWindow);  
  37.                         }  
  38.                     } catch (RemoteException e) {  
  39.                     }  
  40.                 }  
  41.   
  42.                 mSurface.release();  
  43.             }  
  44.         }  
  45.   
  46.         mAdded = false;  
  47.     }  
  48.     WindowManagerGlobal.getInstance().doRemoveView(this);  
  49. }  
(5)doDie方法中调用的dispatchDetachedFromWindow是真正删除View的逻辑。
在doDie方法中调用,实现真正的删除View的逻辑。在这个方法中主要做四件事情:
(1)垃圾回收相关的工作,比如清除数据和消息、移除回调。
(2)通过Session的remove方法删除Window:mWindowSession.remove(mWindow),这同样是一个IPC过程, 最终会调用WindowManagerService的removeWindow方法。
(3)调用View的dispatchDetachedFromWindow方法:
     * 在内部会调用View的onDetachedFromWindow()以及onDetachedFromWindowInternal()。
     * 对于onDetachedFromWindow()大家一定不陌生,当View从Window中移除时,这个方法就会被调用,
     * 可以在这个方法内部做一些资源回收的工作,
     * 比如终止动画、停止线程等。
(4)调用WindowManagerGlobal的doRemoveView方法刷新数据,包括mRoots、mParams以及mDyingViews, 需要将当前Window所关联的这三类对象从列表中删除。
ViewRootImpl.java中dispatchDetachedFromWindow方法:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. void dispatchDetachedFromWindow() {  
  2.     if (mView != null && mView.mAttachInfo != null) {  
  3.         if (mAttachInfo.mHardwareRenderer != null &&  
  4.                 mAttachInfo.mHardwareRenderer.isEnabled()) {  
  5.             mAttachInfo.mHardwareRenderer.validate();  
  6.         }  
  7.         mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);  
  8.         mView.dispatchDetachedFromWindow();  
  9.     }  
  10.   
  11.     mAccessibilityInteractionConnectionManager.ensureNoConnection();  
  12.     mAccessibilityManager.removeAccessibilityStateChangeListener(  
  13.             mAccessibilityInteractionConnectionManager);  
  14.     removeSendWindowContentChangedCallback();  
  15.   
  16.     destroyHardwareRenderer();  
  17.   
  18.     setAccessibilityFocus(nullnull);  
  19.   
  20.     mView.assignParent(null);  
  21.     mView = null;  
  22.     mAttachInfo.mRootView = null;  
  23.     mAttachInfo.mSurface = null;  
  24.   
  25.     mSurface.release();  
  26.   
  27.     if (mInputQueueCallback != null && mInputQueue != null) {  
  28.         mInputQueueCallback.onInputQueueDestroyed(mInputQueue);  
  29.         mInputQueue.dispose();  
  30.         mInputQueueCallback = null;  
  31.         mInputQueue = null;  
  32.     }  
  33.     if (mInputEventReceiver != null) {  
  34.         mInputEventReceiver.dispose();  
  35.         mInputEventReceiver = null;  
  36.     }  
  37.     try {  
  38.         mWindowSession.remove(mWindow);  
  39.     } catch (RemoteException e) {  
  40.     }  
  41.   
  42.     // Dispose the input channel after removing the window so the Window Manager  
  43.     // doesn't interpret the input channel being closed as an abnormal termination.  
  44.     if (mInputChannel != null) {  
  45.         mInputChannel.dispose();  
  46.         mInputChannel = null;  
  47.     }  
  48.   
  49.     unscheduleTraversals();  
  50. }  

(7)整体的调用关系是:

ViewManager  -->> WindowManager(继承自ViewManager) -->> WindowManagerImpl(继承自WindowManager) -->>WindowManagerGlobal(WindowManagerImpl内部的一个对象) -->> ViewRooImpl.die(ViewRooImpl是WindowManagerGlobal的removeView方法中的一个对象) -->> doDie(die中的一个方法调用,判断异步还是同步删除) -->> dispatchDetachedFromWindow(在doDie方法中调用,真正用于删除View的逻辑) -->> 通过Session的remove方法删除Window(IPC过程) -->> WindowManagerService.removeWindow -->> dispatchDetachedFromWindow(这个是子View的dispatchDetachedFromWindow方法) -->> onDetachedFromWindow和onDetachedFromWindowInternal(都是子View中的) -->> WindowManagerGlobal.doRemoveView


4、Window的更新过程


(1)从WindowManagerGlobal的updateViewLayout方法看起:
首先它需要更新View的LayoutParams并替换掉老的LayoutParams,接着再更新ViewRootImpl中的LayoutParams,这一步是通过ViewRootImpl的setLayoutParams方法来实现的。在ViewRootImpl中会通过scheduleTraversals方法来对View重新布局,包括测量、布局、重绘这三个过程。除了View本身的重绘以外,ViewRootImpl还会通过WindowSession来更新Window的视图,这个过程最终是由WindowManagerService的relayoutWindow()来具体实现的,它同样是一个IPC过程。
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public void updateViewLayout(View view, ViewGroup.LayoutParams params) {  
  2.     if (view == null) {  
  3.         throw new IllegalArgumentException("view must not be null");  
  4.     }  
  5.     if (!(params instanceof WindowManager.LayoutParams)) {  
  6.         throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");  
  7.     }  
  8.   
  9.     final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;  
  10.   
  11.     /* 
  12.      * 首先它需要更新View的LayoutParams并替换掉老的LayoutParams, 
  13.      * */  
  14.     view.setLayoutParams(wparams);  
  15.   
  16.     synchronized (mLock) {  
  17.         int index = findViewLocked(view, true);  
  18.         ViewRootImpl root = mRoots.get(index);  
  19.         mParams.remove(index);  
  20.         mParams.add(index, wparams);  
  21.         root.setLayoutParams(wparams, false);  
  22.     }  
  23. }  
(2)整体的调用关系是:

ViewManager  -->> WindowManager(继承自ViewManager) -->> WindowManagerImpl(继承自WindowManager) -->>WindowManagerGlobal(WindowManagerImpl内部的一个对象) -->> updateViewLayout(WindowManagerGlobal中的一个方法) -->> setLayoutParams(updateViewLayout方法中调用) -->> ViewRootImpl.setLayoutParams(ViewRootImpl是updateViewLayout中的一个对象) -->> scheduleTraversals方法(在setLayoutParams中调用,在ViewRootImpl中) -->> WindowSession(在ViewRootImpl中,是一个Binder) -->> WindowManagerService.relayoutWindow(具体实现,更新Window的视图,IPC)


四、Window的创建过程


1、Window和View之间的关系


从上面的分析可以得出,View是Android中的视图的呈现方式,但是View不能单独存在,它必须依附在Window这个抽象的概念上面,因此有视图的地方就有Window。
通常视图的表现形式有:Activity、Dialog、Toast、PopUpWindow、菜单等。

2、Activity的Window创建过程


(1)要分析Activity中的Window的创建过程就必须了解Activity的启动过程,详细的启动过程我们会有专门的blog来介绍,我们这里简单的介绍一下。Activity的启动过程很复杂,最终会由ActivityThread中的performLaunchActivity来完成整个启动过程,这个方法内部会通过类加载器创建Activity的实例对象,并调用其attach方法为其关联运行过程中所一来的一系列上下文环境变量,代码如下所示,在ActivityThread.java文件中的performLaunchActivity方法:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1.         Activity activity = null;  
  2.         try {  
  3.             java.lang.ClassLoader cl = r.packageInfo.getClassLoader();  
  4.             /* 
  5.              * 通过类加载器创建Activity的实例对象: 
  6.              * */  
  7.             activity = mInstrumentation.newActivity(  
  8.                     cl, component.getClassName(), r.intent);  
  9.             StrictMode.incrementExpectedActivityCount(activity.getClass());  
  10.             r.intent.setExtrasClassLoader(cl);  
  11.             if (r.state != null) {  
  12.                 r.state.setClassLoader(cl);  
  13.             }  
  14.         } catch (Exception e) {  
  15.             if (!mInstrumentation.onException(activity, e)) {  
  16.                 throw new RuntimeException(  
  17.                     "Unable to instantiate activity " + component  
  18.                     + ": " + e.toString(), e);  
  19.             }  
  20.         }  
  21.   
  22. .....  
  23.             if (activity != null) {  
  24.                 Context appContext = createBaseContextForActivity(r, activity);  
  25.                 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());  
  26.                 Configuration config = new Configuration(mCompatConfiguration);  
  27.                 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "  
  28.                         + r.activityInfo.name + " with config " + config);  
  29.                 activity.attach(appContext, this, getInstrumentation(), r.token,  
  30.                         r.ident, app, r.intent, r.activityInfo, title, r.parent,  
  31.                         r.embeddedID, r.lastNonConfigurationInstances, config);  
  32.   
  33.                ...  
  34.     }  
(2)在Activity的attach方法里,系统会创建Activity所属的Window对象并为其设置回调接口,Window对象的创建是通过PolicyManager的makeNewWindow方法实现的。由于Activity实现了Window的Callback接口,因此当Window接收到外界的状态改变时就会回调Activity的方法。Callback接口中的方法很多,但是有几个确实非常熟悉的,比如onAttachToWindow、onDetachedFromWindow、dispatchTouchEvent等,代码如下,在Activity.java文件中的attach方法中:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. mWindow = PolicyManager.makeNewWindow(this);  
  2. mWindow.setCallback(this);  
  3. mWindow.getLayoutInflater().setPrivateFactory(this);  
  4. if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {  
  5.     mWindow.setSoftInputMode(info.softInputMode);  
  6. }  
  7. if (info.uiOptions != 0) {  
  8.     mWindow.setUiOptions(info.uiOptions);  
  9. }  
(3)从上面的分析可以看出,Activity的Window是通过PolicyManager的一个工厂方法来创建的。但从PolicyManager的类名可以看出,它不是一个普通的类,它是一个策略类。PolicyManager中实现的几个工厂方法全部在策略接口IPolicy中声明了,IPolicy的定义如下,IPolicy.java文件:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * Copyright (C) 2008 The Android Open Source Project 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16.   
  17. package com.android.internal.policy;  
  18.   
  19. import android.content.Context;  
  20. import android.view.FallbackEventHandler;  
  21. import android.view.LayoutInflater;  
  22. import android.view.Window;  
  23. import android.view.WindowManagerPolicy;  
  24.   
  25. /** 
  26.  * {@hide} 
  27.  */  
  28.   
  29. /* The implementation of this interface must be called Policy and contained 
  30.  * within the com.android.internal.policy.impl package */  
  31. public interface IPolicy {  
  32.     public Window makeNewWindow(Context context);  
  33.   
  34.     public LayoutInflater makeNewLayoutInflater(Context context);  
  35.   
  36.     public WindowManagerPolicy makeNewWindowManager();  
  37.   
  38.     public FallbackEventHandler makeNewFallbackEventHandler(Context context);  
  39. }  
在实际的调用中,PolicyManager的真正实现类是Policy类,Policy类中的makeNewWindow方法的实现如下,在Policy.java文件中:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public Window makeNewWindow(Context context) {  
  2.     return new PhoneWindow(context);  
  3. }  
可以看出Window的具体实现确实是PhoneWindow。
注意点一:关于策略类PolicyManager是如何关联到Policy上面的,这个无法从源码中的调用关系中找出,这里猜测可能是由编译环节动态控制的。因为我们找不到IPC的Binder。
(4)到这里Window已经创建完成了,下面分析Activity的视图是如何附属在Window上面的。由于Activity的视图由setContentView方法提供,我们只需要看setContentView方法的实现即可,在Activity.java文件中:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public void setContentView(int layoutResID) {  
  2.     getWindow().setContentView(layoutResID);  
  3.     initActionBar();  
  4. }  
Activity的视图由setContentView方法提供,在这里面Activity将具体实现交给了Window处理,而Window的具体实现是由PhoneWindow, 所以只需要看PhoneWindow的相关逻辑即可。
(5)PhoneWindow的setContentView方法大致遵循如下几个步骤:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1.     @Override  
  2.     public void setContentView(int layoutResID) {  
  3.         // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window  
  4.         // decor, when theme attributes and the like are crystalized. Do not check the feature  
  5.         // before this happens.  
  6.         if (mContentParent == null) {  
  7. <span style="white-space:pre">    </span>/* 
  8. <span style="white-space:pre">    </span>第一步,先要创建DecorView才行: 
  9. <span style="white-space:pre">    </span>*/  
  10.             installDecor();  
  11.         } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {  
  12.             mContentParent.removeAllViews();  
  13.         }  
  14.   
  15.   
  16.         if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {  
  17.             final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,  
  18.                     getContext());  
  19.             transitionTo(newScene);  
  20.         } else {  
  21.         /* 
  22. <span style="white-space:pre">    </span>第二步,将Activity的布局文件添加到DecorView的mContentParent中了: 
  23. <span style="white-space:pre">    </span>*/  
  24.             mLayoutInflater.inflate(layoutResID, mContentParent);  
  25.         }  
  26. <span style="white-space:pre">    </span>/* 
  27. <span style="white-space:pre">    </span>第三步, 
  28. <span style="white-space:pre">    </span>*/  
  29.         final Callback cb = getCallback();  
  30.         if (cb != null && !isDestroyed()) {  
  31.             cb.onContentChanged();  
  32.         }  
  33.     }  
第一步:如果没有DecorView,那么就创建它。这个DecorView是Activity中的顶级View,包含标题栏和内容栏,内容栏的id就是“content”,完整id是android.R.id.content。DecorView的创建过程由installDecor方法来完成,在方法内部会通过generateDecor方法来直接创建DecorView,这个时候DecorView还只是一个空白的FrameLayout:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. protected DecorView generateDecor(){  
  2.     return new DecorView(getContext(), -1);  
  3. }  
为了初始化DecorView的结构,PhoneWindow还需要通过generateLayout方法来加载具体的布局文件到DecorView中,具体的布局文件和系统版本以及主题有关,这个过程如下所示,在PhoneWindow.java文件中的generateLayout方法中:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. View in = mLayoutInflater.inflate(layoutResource, null);  
  2. decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));  
  3. mContentRoot = (ViewGroup) in;  
  4.   
  5. ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);  
其中ID_ANDROID_CONTENT的定义如下,在Window.java文件中:这个id对应的ViewGroup就是mContentParent。
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;  
第二步:将View添加到DecorView的mContentParent中。就是上面的这句话:mLayoutInflater.inflate(layoutResID, mContentParent);。到此为止,Activity的布局文件已经加载到DecorView里面了,由此可以理解Activity的setContentView这个方法的来历了。Activity的布局文件只是被添加到DecorView的mContentParent中。
第三步:回调Activity的onContentChanged方法通知Activity视图已经发生改变。由于Activity实现了Window的Callback接口,于是要通知Activity,使其可以做相应的处理。Activity的onContentChanged方法是个空实现,我们可以在子Activity中处理这个回调。

(6)经过上面的三个步骤,到这里为止DecorView已经被创建并初始化完毕,Activity的布局文件也已经成功添加到了DecorView的mContentParent中,但是这个时候DecorView还没有被WindowManager正式添加到Window中。这里需要正确理解Window的概念,Window更多表示的是一种抽象的功能集合,虽然说早在Activity的attach方法中Window就已经被创建了,但是这个时候由于DecorView并没有被WindowManager识别,所以这个时候的Window无法提供具体功能,因为它还无法接收外界的输入信息。在ActivityThread的handleResumeActivity方法中,首先会调用Activity的onResume方法,接着会调用Activity的makeVisible方法,正是在makeVisible方法中,DecorView真正地完成了添加和显示这两个过程,到这里Activity的视图才能被用户看到,如下所示,在Activity.java文件中:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. void makeVisible() {  
  2.     if (!mWindowAdded) {  
  3.         ViewManager wm = getWindowManager();  
  4.         wm.addView(mDecor, getWindow().getAttributes());  
  5.         mWindowAdded = true;  
  6.     }  
  7.     mDecor.setVisibility(View.VISIBLE);  
  8. }  


(7)整体流程:

ActivityThread -->> (在ActivityThread中的方法)performLaunchActivity -->> (在performLaunchActivity方法中)通过类加载器创建Activity的实例对象 -->> (在performLaunchActivity方法中)调用attach方法来关联运行过程中所依赖的一系列上下文环境变量 -->>  (在attach方法中) -->> 创建Activity所属的Window对象并为其设置回调接口,这里就涉及到了PolicyManager -->> 现在转到Activity的setContentView中 -->> PhoneWindowde的setContentView方法 -->> 在PhoneWindow的setContentView方法中,有三大步骤。完成了DecorView的创建和初始化,Activity的布局文件也成功添加到DecorView中 -->> ActivityThread的handleResumeActivity方法会调用Activity的onResume方法 -->> onResume方法中会调用Activity的makeVisible方法让DecorView真正完成添加和显示过程 -->> 结束 



五、Dialog的Window创建过程


Dialog的Window创建和Activity类似,有如下几个步骤:

1、创建Window


(1)Dialog中Window的创建同样是通过PolicyManager的makeNewWindow方法来完成的,创建的对象实际上就是PhoneWindow,这个过程和Activity的Window的创建过程是一样的。
在Dialog.java文件中:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1.     Dialog(Context context, int theme, boolean createContextThemeWrapper) {  
  2.         if (createContextThemeWrapper) {  
  3.             if (theme == 0) {  
  4.                 TypedValue outValue = new TypedValue();  
  5.                 context.getTheme().resolveAttribute(com.android.internal.R.attr.dialogTheme,  
  6.                         outValue, true);  
  7.                 theme = outValue.resourceId;  
  8.             }  
  9.             mContext = new ContextThemeWrapper(context, theme);  
  10.         } else {  
  11.             mContext = context;  
  12.         }  
  13. //主要看这里:  
  14.         mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);  
  15.         Window w = PolicyManager.makeNewWindow(mContext);  
  16.         mWindow = w;  
  17.         w.setCallback(this);  
  18.         w.setOnWindowDismissedCallback(this);  
  19.         w.setWindowManager(mWindowManager, nullnull);  
  20.         w.setGravity(Gravity.CENTER);  
  21.         mListenersHandler = new ListenersHandler(this);  
  22.     }  

2、初始化DecorView并将Dialog的视图添加到DecorView中


这个也与Activity的类似,都是通过Window去添加指定的布局文件:
在Dialog.java文件中:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. public void setContentView(View view) {  
  2.     mWindow.setContentView(view);  
  3. }  

3、将DecorView添加到Window中并显示


在Dialog的show方法中,会通过WindowManager将DecorView添加到Window中,如下:
在Dialog.java文件中:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. mWindowManager.addView(mDecor, 1);  
  2. mShowing = true;  

以上可以发现Activity的Window创建过程和Dialog的Window创建过程很类似,两者几乎没有什么区别。

4、关闭Dialog


通过WindowManager来移除DecorView:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. mWindowManager.removeViewImmediate(mDecor);  


5、一个注意点


普通的Dialog有一个特殊之处,那就是必须采用Activity的Context,如果采用Application的Context,就会报错。
下面这个第一行是错误的:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. Dialog dailog = new Dialog(this.getApplicationContext());  
  2. TextView textView = new TextView(this);  
  3. textView.setText("this is a toast");  
  4. dialog.setContentView(textView);  
  5. dialog.show();  
报错的信息会说是因为没有应用token所致,而应用token一般只有Activity拥有,所以这里只需要用Activity作为Context来显示对话框即可。另外系统Window比较特殊,它可以不需要token,因此在上面的例子中,只需要指定对话框的Window为系统Window类型就可以正常弹出对话框。我们在上面讲过,WindowManager.LayoutParams中的type表示Window的类型,而系统Window的层级范围是2000~2999,这些层级范围就对应着type参数。系统Window的层级有很多值,对于本例来说,就可以选用TYPE_SYSTEM_OVERLAY来指定对话框的Window类型为系统Window:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. dialog.getWindow().setType(LayoutParams.TYPE_SYSTEM_OVERLAY);  
然后别忘了在AndroidManifest文件中声明权限从而可以使用系统Window,如下所示:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <user-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />  

六、Toast的Window创建过程


1、Toast和Dialog不同,它的工作过程就稍显复杂


(1)Toast也是基于Window来实现的,但是由于Toast具有定时取消的功能,所以系统采用了Handler。
(2)在Toast内部有两类IPC过程,第一类是Toast访问NotificationManagerService,第二类是NotificationManagerService回调Toast里的TN接口。
(3)Toast属于系统Window,它内部的视图由两种方式指定,一种是系统默认的样式,另一种是通过setView方法来指定一个自定义View,不管如何它们都对应Toast的一个View类型的内部成员mNextView。Toast提供了show和cancel分别用于显示和隐藏Toast,它们的内部是一个IPC过程。show和cancle都需要通过NotificationManagerService来实现。
(4)需要注意的是TN这个类,它是一个Binder类,在Toast和NotificationManagerService进行IPC过程中,当NotificationManagerService处理Toast的显示或者隐藏请求时会跨进程回调TN中的方法,这个时候由于TN运行在Binder线程池中,所以需要通过Handler将其切换到当前线程中。这里的当前线程是指发送Toast请求所在的线程。注意,由于这里使用了Handler,所以这意味着ToastRecord无法在没有Looper的线程中弹出,这是因为Handler需要使用Looper才能完成切换线程的功能。
(5)在Toast.java文件中:show方法
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1.     /** 
  2.      * Show the view for the specified duration. 
  3.      */  
  4.     /* 
  5.      * 显示Toast: 
  6.      * 内部是一个IPC过程。 
  7.      * */  
  8.     public void show() {  
  9.         if (mNextView == null) {  
  10.             throw new RuntimeException("setView must have been called");  
  11.         }  
  12.   
  13.   
  14.         /* 
  15.          * 由于NotificationManagerService运行在系统的进程中, 
  16.          * 所以只能通过远程调用的方式来显示和隐藏Toast。 
  17.          * TN是一个Binder类,在Toast和NotificationManagerService进行IPC的过程中, 
  18.          * 当NotificationManagerService处理Toast的显示或隐藏时会跨进程回调TN中的方法, 
  19.          * 这个时候由于TN运行在Binder线程池中,所以需要通过Handler将其切换到当前线程中。 
  20.          * 这里的当前线程指的是发送Toast请求所在的线程。 
  21.          * 注意,由于这里使用了Handler,所以这意味着Toast无法在没有Looper的线程中弹出, 
  22.          * 这是因为Handler需要使用Looper才能完成切换线程的功能。 
  23.          * */  
  24.         INotificationManager service = getService();  
  25.         String pkg = mContext.getPackageName();  
  26.         /* 
  27.          * TN是Binder类,是Toast的内部类 
  28.          * */  
  29.         TN tn = mTN;  
  30.         tn.mNextView = mNextView;  
  31.   
  32.   
  33.         try {  
  34.         <span style="white-space:pre">    </span>/* 
  35.         <span style="white-space:pre">    </span> * IPC体现在,我们这里可以使用NotificationManagerService内部的方法了呢。 
  36.         <span style="white-space:pre">    </span> * 第一个参数:表示当前应用的包名, 
  37.         <span style="white-space:pre">    </span> * 第二个参数:表示远程回调, 
  38.         <span style="white-space:pre">    </span> * 第三个参数:表示Toast的显示时长。 
  39.         <span style="white-space:pre">    </span> * 这个方法首先将Toast请求封装为ToastRecord对象,并将其添加到一个名为mToastQueue的队列中, 
  40.         <span style="white-space:pre">    </span> * mToastQueue其实是一个ArrayList。 
  41.         <span style="white-space:pre">    </span> * 对于非系统应用来说,mToastQueue中最多能同时存在50个ToastRecord, 
  42.         <span style="white-space:pre">    </span> * 这样做是为了防止DOS(Denial of Service),防止拒绝服务攻击。 
  43.         <span style="white-space:pre">    </span> * */  
  44.             service.enqueueToast(pkg, tn, mDuration);  
  45.         } catch (RemoteException e) {  
  46.             // Empty  
  47.         }  
  48.     }  
  49.   
  50.   
  51.     /** 
  52.      * Close the view if it's showing, or don't show it if it isn't showing yet. 
  53.      * You do not normally have to call this.  Normally view will disappear on its own 
  54.      * after the appropriate duration. 
  55.      */  
  56.     /* 
  57.      * 关闭Toast: 
  58.      * 内部是一个IPC过程。 
  59.      * */  
  60.     public void cancel() {  
  61.         mTN.hide();  
  62.   
  63.   
  64.         try {  
  65.             getService().cancelToast(mContext.getPackageName(), mTN);  
  66.         } catch (RemoteException e) {  
  67.             // Empty  
  68.         }  
  69.     }  
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1.      /* 
  2.      * 第一个参数:表示当前应用的包名, 
  3. <span style="white-space:pre">    </span> * 第二个参数:表示远程回调,这个参数是一个Binder类,也就是Toast中的TN对象。 
  4. <span style="white-space:pre">    </span> * 第三个参数:表示Toast的显示时长。 
  5. <span style="white-space:pre">    </span> * 这个方法首先将Toast请求封装为ToastRecord对象,并将其添加到一个名为mToastQueue的队列中, 
  6. <span style="white-space:pre">    </span> * mToastQueue其实是一个ArrayList。 
  7. <span style="white-space:pre">    </span> * 对于非系统应用来说,mToastQueue中最多能同时存在50个ToastRecord, 
  8. <span style="white-space:pre">    </span> * 这样做是为了防止DOS(Denial of Service),防止拒绝服务攻击。 
  9.      * */  
  10.     public void enqueueToast(String pkg, ITransientNotification callback, int duration)  
  11.     {  
  12.         if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);  
  13.   
  14.   
  15.         if (pkg == null || callback == null) {  
  16.             Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);  
  17.             return ;  
  18.         }  
  19.   
  20.   
  21.         final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));  
  22.   
  23.   
  24.         if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {  
  25.             if (!isSystemToast) {  
  26.                 Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");  
  27.                 return;  
  28.             }  
  29.         }  
  30.   
  31.   
  32.         synchronized (mToastQueue) {  
  33.             int callingPid = Binder.getCallingPid();  
  34.             long callingId = Binder.clearCallingIdentity();  
  35.             try {  
  36.                 ToastRecord record;  
  37.                 int index = indexOfToastLocked(pkg, callback);  
  38.                 // If it's already in the queue, we update it in place, we don't  
  39.                 // move it to the end of the queue.  
  40.                 if (index >= 0) {  
  41.                     record = mToastQueue.get(index);  
  42.                     record.update(duration);  
  43.                 } else {  
  44.                     // Limit the number of toasts that any given package except the android  
  45.                     // package can enqueue.  Prevents DOS attacks and deals with leaks.  
  46.                     /* 
  47.                      * 这个方法首先将Toast请求封装为ToastRecord对象,并将其添加到一个名为mToastQueue的队列中, 
  48. <span style="white-space:pre">                    </span> * mToastQueue其实是一个ArrayList。 
  49. <span style="white-space:pre">                    </span> * 对于非系统应用来说,mToastQueue中最多能同时存在50个ToastRecord, 
  50. <span style="white-space:pre">                    </span> * 这样做是为了防止DOS(Denial of Service),防止拒绝服务攻击。 
  51.                      * */  
  52.                 <span style="white-space:pre">    </span>if (!isSystemToast) {  
  53.                         int count = 0;  
  54.                         final int N = mToastQueue.size();  
  55.                         for (int i=0; i<N; i++) {  
  56.                              final ToastRecord r = mToastQueue.get(i);  
  57.                              if (r.pkg.equals(pkg)) {  
  58.                                  count++;  
  59.                                  if (count >= MAX_PACKAGE_NOTIFICATIONS) {  
  60.                                      Slog.e(TAG, "Package has already posted " + count  
  61.                                             + " toasts. Not showing more. Package=" + pkg);  
  62.                                      return;  
  63.                                  }  
  64.                              }  
  65.                         }  
  66.                     }  
  67.   
  68.   
  69.                 <span style="white-space:pre">    </span>/* 
  70.                 <span style="white-space:pre">    </span> * 在ToastQueue中添加的ToastRecord对象的callback字段就是Toast的TN对象。 
  71.                 <span style="white-space:pre">    </span> * */  
  72.                     record = new ToastRecord(callingPid, pkg, callback, duration);  
  73.                     mToastQueue.add(record);  
  74.                     index = mToastQueue.size() - 1;  
  75.                     keepProcessAliveLocked(callingPid);  
  76.                 }  
  77.                 // If it's at index 0, it's the current toast.  It doesn't matter if it's  
  78.                 // new or just been updated.  Call back and tell it to show itself.  
  79.                 // If the callback fails, this will remove it from the list, so don't  
  80.                 // assume that it's valid after this.  
  81.                 if (index == 0) {  
  82.                 <span style="white-space:pre">    </span>/* 
  83.                 <span style="white-space:pre">    </span> * 通过该方法来显示当前的Toast: 
  84.                 <span style="white-space:pre">    </span> * */  
  85.                     showNextToastLocked();  
  86.                 }  
  87.             } finally {  
  88.                 Binder.restoreCallingIdentity(callingId);  
  89.             }  
  90.         }  
  91.     }  
在enqueueToast中首先将Toast请求封装成ToastRecord对象并将其添加到一个名为mToastQueue的队列中。mToastQueue其实是一个ArrayList。对于非系统应用来说,mToastQueue中最多能同时存在50个ToastRecord,这样做是为了防止DOS(Denial of Service),放置拒绝服务攻击。
(6)正常情况下,一个应用不可能达到上限,当ToastRecord被添加到mToastQueue中后,NotificationManagerService就会通过showNextToastLocked方法来显示当前的Toast。
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * 通过showNextToastLocked来显示当前的Toast。 
  3.  * Toast的显示是由ToastRecord的callback字段来完成的, 
  4.  * 这个callback实际上就是Toast中的TN对象的远程Binder, 
  5.  * 通过callback来访问TN中的方法是需要跨进程来完成的, 
  6.  * 最终被调用的TN中的方法会运行在发起Toast请求的应用的Binder线程池中。也就是在客户端中运行的 
  7.  * */  
  8. private void showNextToastLocked() {  
  9.     ToastRecord record = mToastQueue.get(0);  
  10.     while (record != null) {  
  11.         if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);  
  12.         try {  
  13.             /* 
  14.              * 在这里啦:调用Toast中TN对象的show方法: 
  15.              * */  
  16.             record.callback.show();  
  17.             /* 
  18.              * 在Toast显示之后,NotificationManagerService通过该方法来发送一个延时消息, 
  19.              * 具体延时取决于Toast的时长: 
  20.              * */  
  21.             scheduleTimeoutLocked(record);  
  22.             return;  
  23.         } catch (RemoteException e) {  
  24.             Slog.w(TAG, "Object died trying to show notification " + record.callback  
  25.                     + " in package " + record.pkg);  
  26.             // remove it from the list and let the process die  
  27.             int index = mToastQueue.indexOf(record);  
  28.             if (index >= 0) {  
  29.                 mToastQueue.remove(index);  
  30.             }  
  31.             keepProcessAliveLocked(record.pid);  
  32.             if (mToastQueue.size() > 0) {  
  33.                 record = mToastQueue.get(0);  
  34.             } else {  
  35.                 record = null;  
  36.             }  
  37.         }  
  38.     }  
  39. }  
scheduleTimeoutLocked方法:用到了Handler
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * 在Toast显示之后,NotificationManagerService通过该方法来发送一个延时消息, 
  3.  * 具体延时取决于Toast的时长: 
  4.  * */  
  5. private void scheduleTimeoutLocked(ToastRecord r)  
  6. {  
  7.     mHandler.removeCallbacksAndMessages(r);  
  8.     Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);  
  9.     /* 
  10.      * LONG_DELAY:3.5s 
  11.      * SHORT_DELAY:2.5s 
  12.      * */  
  13.     long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;  
  14.     mHandler.sendMessageDelayed(m, delay);  
  15. }  
(7)延迟相应时间后,NotificationManagerService会通过cancelToastLocked方法来隐藏Toast并将其从mToastQueue中移除,这个时候如果mToastQueue中还有其他Toast,那么NotificationManagerService就继续显示其他Toast:
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * Toast的隐藏也是通过ToastRecord的callback来完成的, 
  3.  * 这同样是一次IPC过程,它的工作方式和Toast的显示过程是类似的。 
  4.  * */  
  5. private void cancelToastLocked(int index) {  
  6.     ToastRecord record = mToastQueue.get(index);  
  7.     try {  
  8.         /* 
  9.          * 这个callback就是TN对象,远程调用TN对象的hide方法。 
  10.          * */  
  11.         record.callback.hide();  
  12.     } catch (RemoteException e) {  
  13.         Slog.w(TAG, "Object died trying to hide notification " + record.callback  
  14.                 + " in package " + record.pkg);  
  15.         // don't worry about this, we're about to remove it from  
  16.         // the list anyway  
  17.     }  
  18.     mToastQueue.remove(index);  
  19.     keepProcessAliveLocked(record.pid);  
  20.     if (mToastQueue.size() > 0) {  
  21.         // Show the next one. If the callback fails, this will remove  
  22.         // it from the list, so don't assume that the list hasn't changed  
  23.         // after this point.  
  24.         showNextToastLocked();  
  25.     }  
  26. }  
(8)通过上面的分析,大家知道Toast的显示和影响过程实际上是通过Toast中的TN这个类来实现的,它有两个方法show和hide,分别对应Toast的显示和隐藏。由于这两个方法是被NMS以跨进程的方式调用的,因此它们运行在Binder线程池中。为了将执行环境切换到Toast请求所在的线程,在它们的内部使用了Handler:mShow和mHide分别是两个Runnable,它们内部分别调用了handleShow和handleHide方法。由此可见,handleShow和handleHide才是真正完成显示和隐藏Toast的地方。
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * schedule handleShow into the right thread 
  3.  */  
  4. /* 
  5.  * 在NotificationManagerService中会通过TN对象远程调用TN对象的show方法来实现Toast的显示, 
  6.  * 因此show方法运行在Binder线程池中。 
  7.  * 为了将执行环境切换到Toast请求所在的线程,在它们的内部都使用了Handler, 
  8.  * 所以Toast的显示又跳转到mShow中。 
  9.  * */  
  10. @Override  
  11. public void show() {  
  12.     if (localLOGV) Log.v(TAG, "SHOW: " + this);  
  13.     mHandler.post(mShow);  
  14. }  
  15.   
  16. /** 
  17.  * schedule handleHide into the right thread 
  18.  */  
  19. /* 
  20.  * 在NotificationManagerService中会通过TN对象远程调用TN对象的hide方法来实现Toast的隐藏, 
  21.  * 因此hide方法运行在Binder线程池中。 
  22.  * 为了将执行环境切换到Toast请求所在的线程,在它们的内部都使用了Handler, 
  23.  * 所以Toast的隐藏又跳转到mHide中。 
  24.  * */  
  25. @Override  
  26. public void hide() {  
  27.     if (localLOGV) Log.v(TAG, "HIDE: " + this);  
  28.     mHandler.post(mHide);  
  29. }  
(9)在Toast.java文件中,TN是内部类,它继承了ITransientNotification.Stub,是一个Binder,内部有两个方法show和hide供其他人调用。也就是说如果Toast是服务端,服务端将TN这个Binder传递给NotificationManagerService这个客户端,然后NotificationManagerService通过这个TN对象来调用Toast中的这两个方法,属于IPC远程调用。
[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. private static class TN extends ITransientNotification.Stub {  
  2.       
  3.     /* 
  4.      * mShow是Runnable,内部调用了handleShow方法, 
  5.      * 可见handleShow方法才是真正完成显示Toast的地方。 
  6.      * TN的handleShow中会将Toast的视图添加到Window中。  
  7.      * */  
  8.     final Runnable mShow = new Runnable() {  
  9.         @Override  
  10.         public void run() {  
  11.             handleShow();  
  12.         }  
  13.     };  
  14.   
  15.     /* 
  16.      * mHide是Runnable,内部调用了handleHide方法, 
  17.      * 可见handleHide方法才是真正完成隐藏Toast的地方。 
  18.      * TN的handleHide中会将Toast的视图从Window中移除。  
  19.      * */  
  20.     final Runnable mHide = new Runnable() {  
  21.         @Override  
  22.         public void run() {  
  23.             handleHide();  
  24.             // Don't do this in handleHide() because it is also invoked by handleShow()  
  25.             mNextView = null;  
  26.         }  
  27.     };  
  28.   
  29.     private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();  
  30.     final Handler mHandler = new Handler();      
  31.   
  32.     int mGravity;  
  33.     int mX, mY;  
  34.     float mHorizontalMargin;  
  35.     float mVerticalMargin;  
  36.   
  37.   
  38.     View mView;  
  39.     View mNextView;  
  40.   
  41.     WindowManager mWM;  
  42.   
  43.     TN() {  
  44.         // XXX This should be changed to use a Dialog, with a Theme.Toast  
  45.         // defined that sets up the layout params appropriately.  
  46.         final WindowManager.LayoutParams params = mParams;  
  47.         params.height = WindowManager.LayoutParams.WRAP_CONTENT;  
  48.         params.width = WindowManager.LayoutParams.WRAP_CONTENT;  
  49.         params.format = PixelFormat.TRANSLUCENT;  
  50.         params.windowAnimations = com.android.internal.R.style.Animation_Toast;  
  51.         params.type = WindowManager.LayoutParams.TYPE_TOAST;  
  52.         params.setTitle("Toast");  
  53.         params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON  
  54.                 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE  
  55.                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;  
  56.     }  
  57.   
  58.     /** 
  59.      * schedule handleShow into the right thread 
  60.      */  
  61.     /* 
  62.      * 在NotificationManagerService中会通过TN对象远程调用TN对象的show方法来实现Toast的显示, 
  63.      * 因此show方法运行在Binder线程池中。 
  64.      * 为了将执行环境切换到Toast请求所在的线程,在它们的内部都使用了Handler, 
  65.      * 所以Toast的显示又跳转到mShow中。 
  66.      * */  
  67.     @Override  
  68.     public void show() {  
  69.         if (localLOGV) Log.v(TAG, "SHOW: " + this);  
  70.         mHandler.post(mShow);  
  71.     }  
  72.   
  73.     /** 
  74.      * schedule handleHide into the right thread 
  75.      */  
  76.     /* 
  77.      * 在NotificationManagerService中会通过TN对象远程调用TN对象的hide方法来实现Toast的隐藏, 
  78.      * 因此hide方法运行在Binder线程池中。 
  79.      * 为了将执行环境切换到Toast请求所在的线程,在它们的内部都使用了Handler, 
  80.      * 所以Toast的隐藏又跳转到mHide中。 
  81.      * */  
  82.     @Override  
  83.     public void hide() {  
  84.         if (localLOGV) Log.v(TAG, "HIDE: " + this);  
  85.         mHandler.post(mHide);  
  86.     }  
  87.   
  88.     /* 
  89.      * handleShow方法才是真正完成显示Toast的地方。 
  90.      * TN的handleShow中会将Toast的视图添加到Window中。  
  91.      * */  
  92.     public void handleShow() {  
  93.         if (localLOGV) Log.v(TAG, "HANDLE SHOW: " + this + " mView=" + mView  
  94.                 + " mNextView=" + mNextView);  
  95.         if (mView != mNextView) {  
  96.             // remove the old view if necessary  
  97.             handleHide();  
  98.             mView = mNextView;  
  99.             Context context = mView.getContext().getApplicationContext();  
  100.             if (context == null) {  
  101.                 context = mView.getContext();  
  102.             }  
  103.             mWM = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);  
  104.             // We can resolve the Gravity here by using the Locale for getting  
  105.             // the layout direction  
  106.             final Configuration config = mView.getContext().getResources().getConfiguration();  
  107.             final int gravity = Gravity.getAbsoluteGravity(mGravity, config.getLayoutDirection());  
  108.             mParams.gravity = gravity;  
  109.             if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {  
  110.                 mParams.horizontalWeight = 1.0f;  
  111.             }  
  112.             if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {  
  113.                 mParams.verticalWeight = 1.0f;  
  114.             }  
  115.             mParams.x = mX;  
  116.             mParams.y = mY;  
  117.             mParams.verticalMargin = mVerticalMargin;  
  118.             mParams.horizontalMargin = mHorizontalMargin;  
  119.             if (mView.getParent() != null) {  
  120.                 if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this);  
  121.                 mWM.removeView(mView);  
  122.             }  
  123.             if (localLOGV) Log.v(TAG, "ADD! " + mView + " in " + this);  
  124.             /* 
  125.              * 在这里呢 
  126.              * */  
  127.             mWM.addView(mView, mParams);  
  128.             trySendAccessibilityEvent();  
  129.         }  
  130.     }  
  131.   
  132.     private void trySendAccessibilityEvent() {  
  133.         AccessibilityManager accessibilityManager =  
  134.                 AccessibilityManager.getInstance(mView.getContext());  
  135.         if (!accessibilityManager.isEnabled()) {  
  136.             return;  
  137.         }  
  138.         // treat toasts as notifications since they are used to  
  139.         // announce a transient piece of information to the user  
  140.         AccessibilityEvent event = AccessibilityEvent.obtain(  
  141.                 AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);  
  142.         event.setClassName(getClass().getName());  
  143.         event.setPackageName(mView.getContext().getPackageName());  
  144.         mView.dispatchPopulateAccessibilityEvent(event);  
  145.         accessibilityManager.sendAccessibilityEvent(event);  
  146.     }          
  147.   
  148.     /* 
  149.      * handleHide方法才是真正完成隐藏Toast的地方。 
  150.      * TN的handleHide中会将Toast的视图从Window中移除。 
  151.      * */  
  152.     public void handleHide() {  
  153.         if (localLOGV) Log.v(TAG, "HANDLE HIDE: " + this + " mView=" + mView);  
  154.         if (mView != null) {  
  155.             // note: checking parent() just to make sure the view has  
  156.             // been added...  i have seen cases where we get here when  
  157.             // the view isn't yet added, so let's try not to crash.  
  158.             if (mView.getParent() != null) {  
  159.                 if (localLOGV) Log.v(TAG, "REMOVE! " + mView + " in " + this);  
  160.                 /* 
  161.                  * 在这里呢 
  162.                  * */  
  163.                 mWM.removeView(mView);  
  164.             }  
  165.   
  166.             mView = null;  
  167.         }  
  168.     }  
  169. }  

(10)整体过程:

Toast.show -->> NotificationManagerService的enqueueToast方法(IPC过程) -->> 在enqueueToast方法中Toast被封装成ToastRecord对象并添加到mToastQueue队列中 -->> enqueueToast方法随后调用showNextToastLocked来显示下一个Toast-->> 在showNextToastLocked方法中通过Toast的TN Binder对象回调客户端的show方法进行Toast显示(IPC过程) -->> 在TN的show方法中调用Handler来执行真正的Toast显示,添加到Window中等等 -->> 在showNextToastLocked方法中又调用scheduleTimeoutLocked来设置Toast显示的延时 -->> NotificationManagerService的cancelToastLocked方法来隐藏Toast并将其从mToastQueue中移除 -->> 在cancelToastLocked方法中通过TN调用了hide方法,hide中又调用了Handler来执行真正的Toast隐藏 -->> 如果mToastQueue中还有其他Toast,那么cancelToastLocked就调用showNextToastLocked来显示下一个Toast。


http://blog.csdn.net/zizidemenghanxiao/article/details/50631148


0 0
原创粉丝点击