Research on Android handler and logoff

Source: Internet
Author: User
// Multi-threaded logoff and handler. It does verify that handlemessage () runs in the thread where the handler is created. Private void testlogoff () {class myhandlerthread extends thread {@ overridepublic void run () {// todo auto-generated method stublogger. showlog ("loopthread --> enter"); loopthread. prepare (); logoff. loop (); // if no call is made, handler does not work. // handler thandler = new handler () {// directly created in the thread, it will be suspended, and the log shows that logoff is not called. prepare (); // @ override // public void handlemessage (Message MSG) {// todo auto-generated method stub // If (MSG. what = 1000) {// testlog. showlog ("I have received message 1000"); //} // super. handlemessage (MSG); //}; // thandler. sendemptymessage (1000); logger. showlog ("loopthread --> finish");} public Looper getlooper () {return Looper. myloopthread () ;}} myhandlerthread loopthread = new myhandlerthread (); loopthread. start (); handler thandler = new handler (loopthread. getlooper () {// logoff // use the sub-thread's //. The message is indeed run in the thread related to IT @ overridepublic void handlemessage (Message MSG) {// todo auto-generated method stubif (MSG. what == 1000) {logger. showlog ("I have received message 1000"); // congestion the thread by 3 stry {thread. sleep (3000);} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace () ;}} if (MSG. what == 1001) {logger. showlog ("I have received message 1001");} super. handlemessage (MSG) ;}}; thandler. sendemptymessage (1000); thandler. senddemptymessage (1001 );}

The result is as follows:

01-02 07:50:09.520: D/langren(1248): loopThread --> enter01-02 07:50:09.530: D/langren(1248): I have received message 100001-02 07:50:12.540: D/langren(1248): I have received message 1001

The second message is received only after 3 seconds.

In the main thread (ui thread), if the logoff object is not input when handler is created, the logoff object of the main thread (ui thread) will be used directly (the system has already created it for us ); in other threads, if a handler is not input when it is created, the handler cannot receive and process messages. In this case, the general practice is: Class looperthread extends thread {public handler mhandler; Public void run () {loid. prepare (); mhandler = new handler () {public void handlemessage (Message MSG) {// process incoming messages here}; Looper. loop ();}}

This loop method is an endless loop. It is blocked when messagequeue is empty.

Suddenly realized that the activity may end up blocking in this place, because

In handler. in the sendmessageattime (Message MSG, long uptimemillis) method of Java, we can see that it finds the messagequeue referenced by it, then set the target of the message to itself (in order to find the correct handler in the message processing stage), and then include the message into the message queue. Extract Looper me = mylooper (); messagequeue queue = me. mqueue; while (true) {message MSG = queue. Next (); // might block if (MSG! = NULL) {If (msg.tar get = NULL) {// No target is a magic identifier for the quit message. return;} msg.tar get. dispatchmessage (MSG); MSG. recycle () ;}} in logoff. in the loop () function of Java, we can see that there is an endless loop here, constantly getting the next (next method) message from messagequeue, and then using the target information carried in the message, by the correct handler (dispatchmessage method ).

Wait until an event is generated

Then try to create the default handler in the main thread UI thread

Private handler mhandler = new handler () {public void handlemessage (Message MSG) {Switch (MSG. what) {Case 1003: logger. showlog ("I have received message 1003"); // blocks the thread by 12 stry {thread. sleep (12000); // ANR is displayed, huh, huh} catch (interruptedexception e) {// todo auto-generated catch blocke. printstacktrace () ;}break; default: Break ;}};};

ANR appears.

This is true in the activitythread code.

Public static final void main (string [] ARGs) {samplingprofilerintegration. Start ();...... Looper. preparemainlooper (); If (smainthreadhandler = NULL) {smainthreadhandler = new handler ();} activitythread thread = new activitythread (); thread. Attach (false );...... Logoff. Loop ();...... Thread. Detach ();...... Slog. I (TAG, "main thread of" + name + "is now exiting");} analyze the main method carefully. 2. loity. preparemainlooper (); activitythread is actually the UI thread we often call, that is, the main thread. We all know that the main thread can use handler for asynchronous communication, because the logoff has been created in the main thread, and this logoff is created here. If other threads need to use handler to communicate, they need to create their own logoff. 3. smainthreadhandler = new handler (); Create a handler.

Loop dead loop is the most common message loop mechanism. Distribute messages to the correct places for execution

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.