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