Android Looper Class

Source: Internet
Author: User

5 Essentials for Android Looper class use

1. The Looper class is used to open a message loop for a thread.
By default, the newly born thread in Android does not have a message loop turned on. (except for the main thread, the main thread system automatically creates a Looper object for it, opening the message loop.) )
The Looper object holds messages and events through MessageQueue. A thread can have only one looper, corresponding to a MessageQueue.

2. The handler object is usually used to interact with the Looper. Handler can be seen as an interface to the Looper to send messages and define processing methods to the specified looper.
By default, handler binds to the looper of the thread that is defined, for example, handler is defined in the main thread, which is the looper binding to the main thread.
MainHandler = new Handler () is equivalent to new Handler (Looper.mylooper ()).
Looper.mylooper (): Gets the Looper object of the current process, similar to Looper.getmainlooper () used to get the Looper object of the main thread.

3. In the non-main thread, the direct new Handler () will report the following error:
E/androidruntime (6173): uncaught handler:thread Thread-8 exiting due to uncaught exception
E/androidruntime (6173): Java.lang.RuntimeException:Can ' t create handler inside thread that have not called Looper.prepare ()
The reason is that Looper objects are not created by default in the main thread, and you need to call Looper.prepare () to enable Looper first.

4. Looper.loop (); Let Looper start working, take messages from the message queue, and process the messages.

Note: code written after Looper.loop () will not be executed, the function should be inside a loop, and the loop will not abort until the Mhandler.getlooper (). Quit () is called.

5. Based on the above knowledge, the main thread can send messages to sub-threads (not the main thread).

Android Looper Class

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.