Java Simple simulation handler-message mechanism in Android

Source: Internet
Author: User

It is important that the main thread communicates with the child threads in Android, and Google engineers provide us with a handler-message mechanism to solve their interaction problems. Today, we will simply understand the principle of the handler-message mechanism, and simply simulate the mechanism in Java. Code sample GitHub Address Handlerdemo

First, take a look at the simple flowchart (not quite professional)

It is known that the main related classes in the process are handler, Message, MessageQueue, Looper; let's simply analyze the flowchart around them:

1. We generally create handler in the main thread, then turn on the sub-thread to complete the specified task, and then encapsulate the task data message, sent to handler;

2. Next, MessageQueue receives a message from the handler, sorts it according to the attribute when (time value) in the message, and reorganizes the queue;
(In this section of the MessageQueue: MessageQueue is created in fact with the creation of Looper, and a feature of Looper is that a thread allows only one Looper, slow existence threadlocal<looper >, and Looper's creation Looper.prepare () is called before the handler is created, ensuring that a queue message cached by a MessageQueue is required to be distributed to the looper thread. )

3. Next, the message is removed from the MessageQueue by Looper.loop (), and the Looper.loop () and the next () in MessageQueue are blocked threads, so and the perpetual motive can be used to keep the message out;

4. Finally, the message that Looper.loop () takes out is distributed by using the target (Handler) in messages, and the DispatchMessage (message) method is a method in Handler, which implements the " Who issues the message who handles ", so multiple handler in a thread can achieve relatively independent work.

Next, take a look at the sample code and how it works

code example:

Package Com.wkp.test;import Android.wkp.handler;import Android.wkp.looper;import android.wkp.message;import Java.util.concurrent.executor;import Java.util.concurrent.executors;public class Main {public static void Main (String        [] args) {///main thread Looper prepare Looper.preparemainlooper ();        Create Handler final MainHandler handler = new MainHandler ();        Open thread pool Executor Executor = Executors.newcachedthreadpool ();            for (int i = 0; i < i++) {final int position = i + 1;                        Executor.execute (New Runnable () {@Override public void run () {try {                        Thread.Sleep (position);                            Child Line path task to main thread handler.postdelayed (new Runnable () {@Override public void Run () {System.out.println (Thread.CurrentThread (). GetName () + "         : "+ position);                   }},1000);                        Thread thread = Thread.CurrentThread (); Strand path message to the main thread Message.obtain (handler,position,position,position, "main thread, Hello!                    I am a thread: "+thread.getname ()). Sendtotarget ();                    } catch (Interruptedexception e) {e.printstacktrace ();        }                }            });    }//Message Queuing loop looper.loop (); /** * The main thread handles the message returned by the child thread */private static class MainHandler extends handler{@Override public vo                    ID handlemessage (Message msg) {switch (msg.what) {case Whatconstants.what_one:                    String obj1 = (string) msg.obj;                    System.out.println (OBJ1);                Break                    Case WhatConstants.WHAT_TWO:String obj2 = (String) msg.obj;                    System.out.println (OBJ2);         Break       Case WhatConstants.WHAT_THREE:String obj3 = (String) msg.obj;                    System.out.println (OBJ3);                Break                    Case WhatConstants.WHAT_FOUR:String Obj4 = (String) msg.obj;                    System.out.println (OBJ4);                Break                    Case WhatConstants.WHAT_FIVE:String obj5 = (String) msg.obj;                    System.out.println (OBJ5);                Break                    Case WhatConstants.WHAT_SIX:String obj6 = (String) msg.obj;                    System.out.println (OBJ6);                Break                    Case WhatConstants.WHAT_SEVEN:String OBJ7 = (String) msg.obj;                    System.out.println (OBJ7);                Break                    Case WhatConstants.WHAT_EIGHT:String obj8 = (String) msg.obj;                    System.out.println (OBJ8);     Break           Case WhatConstants.WHAT_NINE:String obj9 = (String) msg.obj;                    System.out.println (OBJ9);                Break                    Case WhatConstants.WHAT_TEN:String obj10 = (String) msg.obj;                    System.out.println (OBJ10);            Break }        }    }}

Operating effect:

主线程,你好!我是线程:pool-1-thread-1main : 1主线程,你好!我是线程:pool-1-thread-2main : 2主线程,你好!我是线程:pool-1-thread-3main : 3主线程,你好!我是线程:pool-1-thread-4主线程,你好!我是线程:pool-1-thread-5main : 4main : 5主线程,你好!我是线程:pool-1-thread-6主线程,你好!我是线程:pool-1-thread-7main : 6main : 7主线程,你好!我是线程:pool-1-thread-8main : 8主线程,你好!我是线程:pool-1-thread-9主线程,你好!我是线程:pool-1-thread-10main : 9main : 10
Finally, friends and relatives are welcome to exchange messages

If you want to know more in-depth, you can watch the source GitHub address, the source code has detailed comments. If you have better ideas or suggestions and good inspiration, please email author, thank you!

QQ e-mail:[email protected]

163 e-mail:[email protected]

Gmail email:[email protected]

Java Simple simulation handler-message mechanism in Android

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.