Android 14th Lesson--handler Looper Message

Source: Internet
Author: User

1. Basic concept

1) Android.os.Handler

2) mainly accepts the data sent by the child thread, and updates the UI with this data in conjunction with the main thread.

3) Once the application is started, the life cycle of the Android UI is started, however, the Android UI thread is not thread-safe, that is, the update UI can only synchronize updates in the main thread, and asynchronous operations in child threads are dangerous. So, if we change the Android UI directly within the new Thread, we will often report an error as follows:

Java.lang.RuntimeException:Can ' t create handler inside thread that have not called

In order to avoid errors, the update Android UI must operate in the main thread, how do you do it? Handler played a special role. The use of handler also brings a lot of relevant knowledge, the following one by one explains.


2. Instantiation

1) Use the default mode new Handler (), which is rarely used in projects. If he is running in the main thread, then the handler object is internally bound to a Looper object Looper.getmainlooper (); What is the Looper object for? The Looper class is used to open a message loop for a thread. You can get the corresponding thread: Handler.getlooper (). GetThread (). By default, the newly born thread in Android does not have the message loop turned on (the main thread is new). In other words, there is a thread object inside Looper that polls for messages that get Message Queuing, which is the Messagequeue,looper object that holds messages and events through MessageQueue, a thread that can have only one looper, Corresponds to a MessageQueue.

The summary is:

A: Handler = new Handler () in the main thread, then this handler internally binds the Looper.getmainlooper () object or Looper.mylooper ();

B: In a child thread, such as Handler = new handler () in thread, then this handler Looper object space-time.

So, how should you register Looper for handler in a child thread? You can use this

Handlerthread handlerthread = new Handlerthread ("Sub thread");

Handlerthread.start (); It is important to provide an environment for the asynchronous running of the thread

Handler = new Handler (Handlerthread.getlooper ());

2) Inherit the way, the inheritance is more Looper object binding method, so the binding is a bit troublesome.

     class MyHandler extends Handler {          public myhandler ()  {          }          public myhandler (Looper looper)  {             super (Looper);          }          / /  subclasses must override this method to accept data           @Override           public void handlemessage (message msg)  {               // msg.what  make a decision, call the corresponding method update ui          }     }

3) Adopt the Inner class way, the inner class way is similar to the default new handler, the only difference is that the inner class needs to rewrite the Handlemessage method, the meaning is not big, the project often use this way. So why recommend this way? First we define a global private handler, and then define the internal class instantiation of the object, the next time you use the call handler, as long as the Looper object of this handler is the main thread of the looper is good, That is, do not instantiate handler in your thread.


3. Handler Call

1) since everything about Message Queuing has Looper object handling, you don't have to go too far. Now as long as you understand how to use handler, about handler synchronization problem, if handler internal bound is the main thread of the Looper object, then, when we call Handler.post (New Thread ()), This registered thread is actually serial in the main line, not parallel. It's like calling the thread object's Run method instead of the Start method, then it's not much of a point!

2) The time-consuming work of the project should be handled by an asynchronous sub-thread, if you put in the main thread, the interface will appear suspended animation, if 5 seconds has not been completed, you will receive an Android system error "forced shutdown." However, the child thread can not update the main thread of the UI, then the problem comes, how should we combine handler to let the child thread and the main thread parallel it? One way is to use Handlerthread to bind a new Looper object to the current handler object, then you can achieve the above requirements. The better way, of course, is to separate the new thread and invoke the handler object that has been instantiated inside the thread, which is also an asynchronous call.


4 Handler Message Delivery

1) The Message object is bound to handler, and handler can use the sendMessage (message) to send the message object to the handler Handlemessage method. In general, we use the Message.what method as the identity of different message types, and the two parameters of message arg1 and arg2 are relatively efficient because they consume less system performance.

2) The Bundle object is a member variable of handler, which can be regarded as a special map object, both are used to cache the data, but the bundle key can only be string, and the method of bundle is more rich than map. In addition, bundle objects are not limited to handler, and are visible everywhere in intent or in the OnCreate method of activity.


Summarize:

It is not possible to update the Android UI directly in a child thread, which requires handler processing, while handler processing requires that the internal Looper object is already bound, and if there is no binding, you need to register a looper manually. Appropriate processing is also required for synchronous or asynchronous calls.


Android 14th Lesson--handler Looper Message

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.