Basic Android tutorial -- 10.7 WindowManager (Window Management Service)

Source: Internet
Author: User

Basic Android tutorial -- 10.7 WindowManager (Window Management Service)
Basic Android tutorial -- 10.7 WindowManager (Window Management Service)

Tags (separated by spaces): basic Android tutorial

This section introduces:

WindowManager (Window Management Service) in the system service provided by Android in this section ),
It is the bottom layer of the display View. The underlying layers of Toast, Activity, and Dialog all use this WindowManager,
It's global! The core of this class is nothing more than calling addView, removeView, and updateViewLayout.
To display the View and SET related properties through the WindowManager. LayoutParams API!
In this section, we will discuss some application instances of WindowManager in actual development ~
Official API documentation: WindowManager

1. Some Concepts of WindowManager: 1) WindowManager Introduction

Android provides an API for interacting with the window manager! We all know that the App interface is
An Activity is composed of multiple Acitivty and a View. When we want to display an interface,
The first thing that comes to mind is Activity, right? Or Dialog and Toast.
However, in some cases, the above three may not meet our needs. For example, we are just a simple display
The use of Activity seems a little redundant, and the Dialog requires Context object, Toast can not be clicked...
In the above cases, we can use WindowManager to add a View to the screen,
Or remove the View from the screen! It is an interface for managing the Android window mechanism and displays the bottom layer of the View!

2) how to obtain the WindowManager instance

Obtain WindowManager objects:

WindowManager wManager = getApplicationContext().getSystemService(Context. WINDOW_ SERVICE);

Obtain the WindowManager. LayoutParams object to prepare for subsequent operations.

WindowManager.LayoutParams wmParams=new WindowManager.LayoutParams();
2. WindowManager instance: Instance 1: Get screen width and height

Before Android 4.2, we can use the following methods to obtain the screen width and height:

    public static int[] getScreenHW(Context context) {        WindowManager manager = (WindowManager)context        .getSystemService(Context.WINDOW_SERVICE);        Display display = manager.getDefaultDisplay();        int width = display.getWidth();        int height = display.getHeight();        int[] HW = new int[] { width, height };        return HW;    }

The above method is outdated after Android 4.2. We can use another method to obtain the screen width and height:

    public static int[] getScreenHW2(Context context) {        WindowManager manager = (WindowManager) context.        getSystemService(Context.WINDOW_SERVICE);        DisplayMetrics dm = new DisplayMetrics();        manager.getDefaultDisplay().getMetrics(dm);        int width = dm.widthPixels;        int height = dm.heightPixels;        int[] HW = new int[] { width, height };        return HW;    }

Then we can write two other methods to get the width and height. Here we take the second method to get the screen width and height as an example:

    public static int getScreenW(Context context) {        return getScreenHW2(context)[0];    }    public static int getScreenH(Context context) {        return getScreenHW2(context)[1];    }

Of course, if you do not write another tool class, you can directly obtain it, for example:

Public class MainActivity extends AppCompatActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); WindowManager wManager = (WindowManager) getSystemService (Context. WINDOW_SERVICE); DisplayMetrics dm = new DisplayMetrics (); wManager. getdefadisplay display (). getMetrics (dm); Toast. makeText (MainActivity. this indicates the screen width and height of the current mobile phone: + dm. widthPixels + * + dm. heightPixels, Toast. LENGTH_SHORT ). show ();}}

Running result:

Example 2: set full screen display in the window
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,                WindowManager.LayoutParams.FLAG_FULLSCREEN);        getSupportActionBar().hide();

Running result:

Instance 3: Keep the screen always on
public void setKeepScreenOn(Activity activity,boolean keepScreenOn)  {      if(keepScreenOn)      {          activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);      }else{          activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);      }  }  
Example 4: Implementation of a simple floating box

Run:

Implementation Code:

First, we need a background Service to wait for our operations in the background, for example, to complete the painting and removal of the floating frame,
Therefore, we define a Service:MyService. java:
We need a method to create a floating box View:

Private void createWindowView () {btnView = new Button (getApplicationContext (); btnView. setBackgroundResource (R. mipmap. ic_launcher); windowManager = (WindowManager) getApplicationContext (). getSystemService (Context. WINDOW_SERVICE); params = new WindowManager. layoutParams (); // set Window Type params. type = WindowManager. layoutParams. TYPE_SYSTEM_ALERT; // you cannot touch params in the floating box. flags = WindowManager. layoutParams. FLAG_NOT_TOUCH_MODAL | WindowManager. layoutParams. FLAG_NOT_FOCUSABLE; // The floating window cannot be touched, no events are accepted, and the subsequent event response params is not affected. format = PixelFormat. RGBA_8888; // set the width and height of the Floating Box params. width = 200; params. height = 200; params. gravity = Gravity. LEFT; params. x = 200; params. y = 000; // set the Touch listening btnView of the floating box. setOnTouchListener (new View. onTouchListener () {// save int lastX, lastY; int paramX, paramY; @ Override public boolean onTouch (View v, MotionEvent event) {switch (event. getAction () {case MotionEvent. ACTION_DOWN: lastX = (int) event. getRawX (); lastY = (int) event. getRawY (); paramX = params. x; paramY = params. y; break; case MotionEvent. ACTION_MOVE: int dx = (int) event. getRawX ()-lastX; int dy = (int) event. getRawY ()-lastY; params. x = paramX + dx; params. y = paramY + dy; // update the windowManager position of the floating window. updateViewLayout (btnView, params); break;} return true ;}}); windowManager. addView (btnView, params); isAdded = true ;}

Then, we only need to call the createWindowView () method in the OnCreate () method to start loading the floating box,
However, we found that this stuff seems to be unable to be shut down. Well, let's analyze the requirements!
This is displayed only when it is on the mobile phone's normal interface, that is, the desktop. When we start other apps, this floating box should
Disappear. When we launch an app and return to the desktop, this floating box will appear again!
First, we need to determine whether the App is on the desktop. Therefore, we need to add the following code:

/*** Determine whether the current interface is desktop */public boolean isHome () {if (mActivityManager = null) {mActivityManager = (ActivityManager) getSystemService (Context. ACTIVITY_SERVICE);} List
  
   
RRTI = mActivityManager. getRunningTasks (1); return homeList. contains (rrps. get (0 ). topActivity. getPackageName ();}/*** get the application package name of the desktop application * @ return returns the string List containing all Package Names */private List
   
    
GetHomes () {List
    
     
Names = new ArrayList
     
      
(); PackageManager packageManager = this. getPackageManager (); // attribute Intent intent = new Intent (Intent. ACTION_MAIN); intent. addCategory (Intent. CATEGORY_HOME); List
      
        ResolveInfo = packageManager. queryIntentActivities (intent, PackageManager. required); for (ResolveInfo ri: resolveInfo) {names. add (ri. activityInfo. packageName);} return names ;}
      
     
    
   
  

Well, next we need to make a series of judgments at intervals, for example, whether a floating box is mounted on the desktop or not,
Otherwise, the floating box will be removed! Here we use handler ~, Because it cannot be directly stored in the subthread
Update the UI, so, you know, so we write a handler to complete the above operations:

// Define the Handler private Handler mHandler = new Handler () {@ Override public void handleMessage (Message msg) {switch (msg. what) {case HANDLE_CHECK_ACTIVITY: if (isHome () {if (! IsAdded) {windowManager. addView (btnView, params); isAdded = true; new Thread (new Runnable () {public void run () {for (int I = 0; I <10; I ++) {try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} Message m = new Message (); m. what = 2; mHandler. sendMessage (m );}}}). start () ;}} else {if (isAdded) {windowManager. removeView (btnView); isAdded = false ;}} mHandler. sendEmptyMessageDelayed (HANDLE_CHECK_ACTIVITY, 0); break ;}}};

The last thing to do is to rewrite the onStartCommand () method of the Service, that is, to make a judgment and retrieve
Data to determine whether to add or remove a floating box!

@Override      public int onStartCommand(Intent intent, int flags, int startId) {          int operation = intent.getIntExtra(OPERATION, OPERATION_SHOW);          switch(operation) {          case OPERATION_SHOW:              mHandler.removeMessages(HANDLE_CHECK_ACTIVITY);              mHandler.sendEmptyMessage(HANDLE_CHECK_ACTIVITY);              break;          case OPERATION_HIDE:              mHandler.removeMessages(HANDLE_CHECK_ACTIVITY);              break;          }          return super.onStartCommand(intent, flags, startId);      }  

Okay, now the main work is complete. Next, there are some fragmented things. Use an Activity
To start this Service:MainActivity. java:

Public class MainActivity extends AppCompatActivity implements View. onClickListener {private Button btn_on; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); bindViews ();} private void bindViews () {btn_on = (Button) findViewById (R. id. btn_on); btn_on.setOnClickListener (this) ;}@ Override public void onClick (V Iew v) {switch (v. getId () {case R. id. btn_on: Intent mIntent = new Intent (MainActivity. this, MainService. class); mIntent. putExtra (MainService. OPERATION, MainService. OPERATION_SHOW); startService (mIntent); Toast. makeText (MainActivity. this, the floating box is enabled ~, Toast. LENGTH_SHORT). show (); break ;}}}

Then add permissions to AndroidManifest. xml and register for MainService:

    
      
       
    
   
  

Well, the logic is easy to understand ~ Let's take a look ~

3. Document extension:

From the fourth instance, you may have noticed WindowManager. LayoutParams, which is a tag,
For example, full screen ~ The time relationship is not listed one by one. You can go to the official website or the following link to view it:

Official documentation: WindowManager. LayoutParams
Android system service-WindowManager

In addition, if you are interested in the above floating box and want to study it more deeply, you can see Guo's blog:

Android desktop floating window effect, imitation 360 mobile guard floating window Effect
Android desktop floating window advanced, QQ mobile phone Butler little rocket effect implementation

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.