preface

This post has been posted on my Github blog. Welcome to my humble abode:

My GIthub blog

This article has authorized the public account Guo Lin, Qin Zishuai

Study list:

  • Window&WindowManagerService

  • Window&WindowManager

  • Window&PhoneWindow

  • Window&Activity

  • Window&View

  • Window internal mechanism

  • Window creation process

1. Why studyWindow?

All views on Android phones are presented by Window, such as commonly used activities, Dialog, PopupWindow and Toast. Their views are attached to Window, so it can be said that “Window is the direct manager of View”.

A Window is an abstract base class for top-level Window viewing and behavior, and an instance of this class is added to the Window Manager as a top-level View. It provides a standard set of UI methods, such as adding backgrounds, titles, and so on.

Window itself is very abstract. An in-depth understanding of Window will not only help you understand the relationship between different levels in the Android system, but also give you a deeper understanding of Toast’s internal mechanism, customization and other aspects.

Window

Note: The StatusBar is also included in the DecorView

Two. Induction of core knowledge points

2.1 WindowRelationship analysis

See the following big picture, is not feeling a little messy, don’t worry, don’t worry, impatient can’t eat hot tofu, the author will tell you

Window overall diagram

2.1.1 Window&PhoneWindow

Before the author advanced the road | wonderful trip to the View, when mentioning the setContentView simple said to the Window and PhoneWindow, believe seen readers have had a simple impression.

Window is an abstract class that defines the top-level form style and behavior. Its only implementation class is PhoneWindow.

The composition of the Activity

2.1.2 Window&View

Before the author advanced the road | wonderful trip to the View, it comes to the View workflow simply by ViewRootImpl, believe that have seen the reader already have a simple impression.

Each Window corresponds to a View and a ViewRootImpl, and the Window and View are linked by the ViewRootImpl. The Window is not visible, it actually exists as a View, and it is the direct manager of the View.

2.1.3 Window&WindowManagerService

Want to know the reader, the IPC may have a look the author to write a blog: advanced road | wonderful journey of IPC

The concrete implementation of Window is in WindowManagerService. The interaction between WindowManager and WindowManagerService is an IPC (cross-process communication) process.

2.1.4 Window&WindowManager

In practice, the Window cannot be accessed. Access to the Window must go through WindowManager (in other words, WindowManager is the entry point for the outside world to access the Window), and operations to the Window are done through it.

  • For example: throughWindowManageraddWindow
// Add a Button to the screen position of (100,300)
mFloatingButton = new Button(this);
mFloatingButton.setText("test button");

mLayoutParams = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.0,PixelFormat.TRANSPARENT);// The third argument represents flags and the fourth argument represents type

mLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
        | LayoutParams.FLAG_NOT_FOCUSABLE
        | LayoutParams.FLAG_SHOW_WHEN_LOCKED;/ / configure flags
mLayoutParams.type = LayoutParams.TYPE_SYSTEM_ERROR;/ / configuration type
mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;/ / configuration gravity
mLayoutParams.x = 100;// Relative to gravity
mLayoutParams.y = 300;// Relative to gravity

mFloatingButton.setOnTouchListener(this);
mWindowManager.addView(mFloatingButton, mLayoutParams);
Copy the code

Here are the three important WindowManager parameters in turn:

  • flagsSaid:WindowProperties. The main meanings of the optional values:
  • FLAG_NOT_FOCUSABLESaid:WindowThere is no need to get focusAnd there is no need to receive various input events. The flag is fired at the same timeFLAG_NOT_TOUCH_MODEL, and eventually the event is passed to the lower level with the focusWindow
  • FLAG_NOT_TOUCH_MODAL: indicates that the system will change the current valueWindowareaoutsideClick event ofPassed to the underlying layerWindow, and regionalwithinClick event ofTake care of. generallyNeed to openThis mark, otherwise othersWindowThe click event will not be received
  • FLAG_SHOW_WHEN_LOCKEDSaid:WindowCan be displayed on the lock screen
  • Type: Indicates the Window type.

    There are three types of Windows:

    A. Application class Window: corresponds to an Activity or Dialog

    B. Child Window: cannot exist alone and must be attached to a specific parent Window. Such as PopupWindow, ContextMenu OptionMenu

    Note: ContextMenu,OptionMenu are subclasses of Dialog that modify their window type

    C. System Window: The system can be created only after the permission is specified. Such as Toast

    • TYPE_SYSTEM_OVERLAY/TYPE_SYSTEM_ERROR

    • Remember to declare permissions: < USES – the permission of the android: name = “android. Permission. SYSTEM_ALERT_WINDOW” / >, Android6.0 the following statement permissions can be directly, Android6.0 above also need users to open the software Settings page to manually open, to authorize.

  • WindowIt is layered, as shown in the table below
  • The big onecoverIn the hierarchy of smallWindowThe above.
  • The correspondingWindowManager.LayoutParamsthetypeParameters.
Window The hierarchy
applicationWindow 1-99.
The childWindow 1000-1999.
systemWindow 2000-2999.
  • gravitySaid:WindowThe location of the.
  • The default is the middle of the screen
  • x,yValue relative to thegravity

2.2 WindowThe internal mechanism of

  • WindowManager has three main operations on Windows: add, update, and delete.

    These three methods are defined primarily in the ViewManager interface:

public interface ViewManager
{
    public void addView(View view, ViewGroup.LayoutParams params);// Add process
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);// Update process
    public void removeView(View view);// Delete process
}
Copy the code
  • WindowManagerIt’s also an interface, it inheritsViewManagerInterface:
public interface WindowManager extends ViewManager {}
Copy the code
  • WindowManagerThe concrete implementation class ofWindowManagerImpl:
public final class WindowManagerImpl implements WindowManager{
        @Override
        public void addView(View view, ViewGroup.LayoutParams params){
            mGlobal.addView(view, params, mDisplay, mParentWindow);
        }
<span class="hljs-meta" style="color: #61aeee; line-height: 26px;" >@Override</span> <span class="hljs-function" style="line-height: 26px;" ><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;" >public</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;" >void</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;" >updateViewLayout</span><span class="hljs-params" style="line-height: 26px;" >(View view, ViewGroup.LayoutParams params)</span></span>{ mGlobal.updateViewLayout(view, params); } <span class="hljs-meta" style="color: #61aeee; line-height: 26px;" >@Override</span> <span class="hljs-function" style="line-height: 26px;" ><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;" >public</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;" >void</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;" >removeView</span><span class="hljs-params" style="line-height: 26px;" >(View view)</span></span>{ mGlobal.removeView(view, <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;" >false</span>); }Copy the code

Copy the code

}

  • As you can see from the above code,WindowManagerImplnodirectlyimplementationWindowOf the three major operations, but handed overWindowManagerGlobal.WindowManagerGlobalIn order toThe singleton patternTo provide an instance of oneself:

WindowManagerImpl This working mode is typical bridge mode

private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
Copy the code

A diagram illustrates the relationship between these classes:

Type of relationship

Therefore, WindowManager can add, delete, and modify Windows through addView(), updateViewLayout(), and removeView() of Windows Global.

2.2.1 WindowThe addition of

Window add process

2.2.2 WindowThe deletion of

Window deletion process

2.2.3 WindowThe update of

Window update process

It is not hard to see that the above verifies the previous summary:

  • WindowAll three operations will eventually pass oneIPCProcess handover toWindowManagerService.
  • WindowandViewthroughViewRootImplTo contact,ViewRootImplCan be controlledViewMeasurement, layout and redrawing of.

Due to lack of space, I have not posted the source code here, but if you want to know, I recommend an article: Windows create/add/remove/update process in my eyes

2.3 WindowThe creation process of

Since a View must be attached to a Window to render it, there must be a Window wherever there is a View. Android provides views for activities, Dialog and Toast, PopupWindow and menu. The following shows the general creation process of three types of Windows: Activity, Dialog and Toast

2.3.1 ActivitytheWindowThe creation process

Want to learn more about the Activity of the startup process, recommend an article I wrote: advanced road | wonderful trip to four major components

Window creation for the Activity

For readers who want to know the source code of the Activity Window creation process, I recommend an article: Analysis of the Activity Window creation process

2.3.2 DialogtheWindowThe creation process

Dialog Window creation process
  • Dialog.show()Completed:DecorViewThe display of the
  • WindowManager.remoteViewImmediate()Methods: whenDialogbedismissWhen removing theDecorView

2.3.3 ToasttheWindowThe creation process

Q1: The internal view of Toast is specified in two ways:

  • Default system style
  • throughsetView()Specify a customView

Q2: Toast has the scheduled cancellation function, so the system uses Handler for scheduled processing

Q3: There are two types of IPC processes within Toast:

  • ToastaccessNotificationManagerService(NotificationManagerServiceProcesses running on the system);
  • NotificationManagerServiceThe callbackToastIn theTNInterface (runs inBinderThread pool).

Q4: Toast provides methods show() and cancel() to show and hide Toast, respectively.

  • ToastBoth show and hide are required throughNMSTo achieve, becauseNMSRunning on theSystem processesMedium, so you need to passThe remote invocationThe way to show and hide Toast.
  • NMSTo deal withToastThe show and hide requests are called back across processesTNBut because ofTNRun in * *BinderThread pool **, so need to passHandlerSwitch it to the current thread (sendToastRequested thread).
  • NMSIt just helpedmanagementToastThe queueAnd itsTime delayThe effect of
  • ToastThe show and hide is actually throughTNTo achieve.
Toast’s Window creation process

Toast Dialog, PopupWindow, Toast

Class quiz

Congratulations to you! After reading the previous article, I believe you have a certain depth of understanding of Windows. Now, let’s take a quiz in class to verify your learning achievements.

Q1: How many Windows are there in an application?

Answer: an infinite number. Reason: Every View is attached to a Window. An application can have an infinite number of views, and so can Windows.

Q2: Do Window objects exist at all?

  • Doubt points:WindowThings that can be done,ViewObjects can do almost anything: things like touch events and manage individual childrenViewAnd so on.
  • Some people might say,”WindowisViewManagers.”
  • Follow-up: We know,WindowManagerisWindowSo why not just use itWindowManagermanagementView?
  • Answer: From the system’s point of view, the system “doesn’t know” there isViewObject of this saying! As a system, I am proud of myself, leaving you aloneWindowHow to move bricks, how to build walls, only give you land. And then,WindowIn order to draw the components the user wants (buttons, text, input fields, etc.), the system won’t give it to me! That’s fine. I’ll define it, so I didViewMechanism, to eachViewprovideCanvas, let differentViewDraw your own unique components. At the same time, for better managementView, by definitionViewGroup, and so on.

Q3: Is Activity necessary?

  • Doubt points:WindowIt is a window for system management. So why is it neededActivity? We put theActivityWhat you do, all encapsulated intoWindowWouldn’t it be all right? Floating windowDialogChinese is not usedActivityTo display a floating window?
  • The answer:AndroidIn the application, the management of each window is quite complex (task stack, state, etc.). But if you let the users manage that themselvesWindowNot to mention the workload, it is difficult for users to implement the task stack on their own. To make it easy and fast for you to develop applications,AndroidletActivityTo help us manage this, we simply need to rewrite a few callback functions, without directly contacting theWindowObject contact.

Everything has rules, the language difficult again, also invented, as a social, in fact this several relations as officials in the country’s central system allocation, historically, a layer of a layer is responsible for, so do their job, and layers to contact each other, to achieve maximum efficiency, suddenly found that the wisdom of the ancients or fierce of, You let the emperor (system) to control all the officials (view), will not be tired to death? That’s why you have these officials in the middle.


If the article is a little help to you, I hope you can click on it. Your click on it is my motivation

References:

  • Exploring the Art of Android Development
  • The bridge model
  • The Window creation/add/remove/update process in my eyes
  • Analyze the Window creation process of the Activity
  • Android Dialog box Dialog, PopupWindow, Toast implementation mechanism
  • Learning introductory notes | AS (one day)
  • Point refined art | the development of the Window
  • Explore the Android Window mechanism
  • Clarify the relationship between activities, Views, and Windows
  • After the android 6.0 android. Permission. SYSTEM_ALERT_WINDOW usage changes
  • How many Windows does an app have?
  • A brief analysis of Android Windows
  • Does the DecorView contain a Status Bar?

This article is formatted using MDNICE