Android four components of activity-(1) from the source to understand and skillfully use Onwindowfocuschanged (Boolean hasfocus)

Source: Internet
Author: User

Starting here, I want to make some summaries and records of the Android four components and some system components while there is time. Because there are already many well-written and comprehensive articles on the web. I also in the bag shy dare not caught dead, record some of the useful knowledge points that I feel important, By the way, we'll learn to talk about anything.


Activity as one of the four components, there is no need to go into the matter of how important it is to develop the entire Android. About its life cycle, here to borrow the diagram of the Xia Guan Net, then at a glance:


So what does its life cycle have to do with what we call the Onwindowfocuschanged (Boolean hasfocus) approach?


The activity life cycle originates from oncreate (), so we put a lot of data initialization here, the persistence of the data is placed in OnStop () OnPause () and OnDestroy () and other methods,  The consistency save processing of temporary data is placed in onsaveinstancestate () and so on.  That's a question, activity as a component container for various layout controls, have you ever tried to make sure that the width of one of our components is not 0, but when we use GetWidth () getheight () for that component, we find that the width and height value we get is 0? Since this time in OnCreate () where the view initialization of Setcontentview () and the measurement of individual components are not completed, we have already called getwidth () GetHeight () two methods.


Trace the source, you will find activity in the process of initializing the view, will call Onmeasure () onlayout () OnDraw () and other methods, to draw the component, the measurement component simultaneously refreshes the current view, Until the initialization of the entire view is complete. How do we know that activity completes the initialization of the view at the appropriate time to use GetWidth () getheight ()? Here's a way to use Onwindowfocuschanged (Boolean hasfocus);


We looked through the activity source and found that onwindowfocuschanged (Boolean Hasfocus) appeared in the two classes of Window$callback and View.java. The method used in Window$callback is actually from View.java. So let's see how this approach is in view:

     /** * This method is invoked when the current window Gets or loses focus. Note that the focus and view focus are separate, and in order to get key events, the View and view window must have the focus. If a window is in your input     * At the top of the event, the window will lose focus and the focus of the view will remain unchanged.  * Called when the window containing this view gains or loses focus. Note * That's separate from view focus:to receive key events, both * your view and its window must has FOC  us. If a window is displayed * On top of yours This takes input focus, then your own window would lose * focus but the     View focus would remain unchanged.     * * @param haswindowfocus True If the window containing this view now has * focus, false otherwise. */public void onwindowfocuschanged (Boolean haswindowfocus) {//Get soft keyboard Inputmethodmanager IMM = Inputmethodman        Ager.peekinstance ();                if (!haswindowfocus) {if (ispressed ()) {///keyboard has an event pressed, forces all child controls contained in the view to be setpressed () set to False            Setpressed (FALSE); } if (IMM! = null && (mprivateflags& FOCUSED)! = 0) {//This is a hidden method (with @hide tag) that calls the method Imm.focusout (this) when the view loses focus;            }//Remove long press Event callback interface method Removelongpresscallback ();            Remove the touch detector, called "Remove the Tap detection timer."            Removetapcallback ();        When the focus (Fucos) is called from the press to cancel, it belongs to the hidden Method Onfocuslost (); } else if (IMM! = null && (Mprivateflags & FOCUSED)! = 0) {//Call this method when the view receives focus, belongs to the hidden method imm        . Focusin (this);    }//Force view to flush drawable state, and will callback Drawablestatechanged () method Refreshdrawablestate (); }

The source notes have been written, it should be seen that the focus of the window and the focus of the view is separate, this method onwindowfocuschanged (Boolean Hasfocus) is the trigger time of the callback is the window to get or lose focus.


So when a new activity is created, the first time to get the focus is where to call this method? See Source:

     /** * called {@link #onRestoreInstanceState}, {@link #onRestart}, or * {@link #onPause}, for your Activ     ity to start interacting with the user.     * This was a good place to begin animations, open exclusive-access devices * (such as the camera), etc. * * from the official note below, this paragraph "use {@link #onWindowFocusChanged} to know for certain." * you know, after the Onresume () method, Onwindo is called Wfocuschanged () Method ~ * * * <p>keep in mind ' onresume is not ' the best indicator ' your activity * is visible to the user;  A system window such as the Keyguard is in * front. Use {@link #onWindowFocusChanged} to know for certain this your * activity is visible to the user (for example, to Res     Ume a game).  * * <p><em>derived classes must call through to the Super class ' s * implementation of this method. If they don't, an exception would be is * thrown.</em></p> * * @see #onRestoreInstanceState * @s   EE #onRestart  * @see #onPostResume * @see #onPause */protected void Onresume () {getapplication (). Dispatchactivityr        Esumed (this);    Mcalled = true; }


It can be seen that the first call to Onwindowfocuschanged () is followed by the Onresume () method when the window in the activity gets the focus. After that, the normal window loses or re-acquires the focus, and so on.

So let's think about what happens when the window loses or gets the focus.

1, after the first entry into an activity, it is called after the Onresume () method

2, jump from activity to another activity. The new window will get the focus, and the activity window will lose focus.

3, open the soft keyboard for input, the window loses focus.

4, soft keyboard input complete disappears, window regain focus

5, Application background, window loses focus

6, the app returns the current from the background, the window gets the focus again

... ...

All of these things will call the Onwindowfocuschanged () method.


Well, from the source to understand why and when to call this method, then look at how to use it skillfully? Give a chestnut:


Skillfully Use one:

When the activity comes to Onresume (), the view is initialized. At the beginning of the article, it was mentioned that the view initialization is not over yet. The achievement call GetWidth () getheight () Gets the width high value is 0. So now the way to get the wide-high method in onwindowfocuschanged (), you will find that the width of the obtained is correct ~


Skillfully use two:

If you want to save and restore some data, you can do this when the app is turned back into the background by the user's home key, or when the app becomes the foreground from the background. Of course, this is not the only choice, but also can be placed in OnPause (), Onresume () and other methods to go. Just say, when you know the role of onwindowfocuschanged (), here we can one more choice, not very good.


There are other uses, of course, to refer to the timing of triggering the onwindowfocuschanged () method mentioned above. At the same time, we can not use, know more, understand a little more, we can make a better choice and implementation. Here's the article, Good night.




Android four components of activity-(1) from the source to understand and skillfully use Onwindowfocuschanged (Boolean hasfocus)

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.