Asynchronous Message Processing Mechanism-Handler principle in Android (continued)

Source: Internet
Author: User

Asynchronous Message Processing Mechanism-Handler principle in Android (continued)

The Asynchronous Message Processing thread refers to the infinite loop that the thread enters after it starts. Each cycle is performed once, a message is taken from the internal message queue and the corresponding message processing function is called back. Generally, the asynchronous message processing thread is used when tasks are resident, such as user interaction tasks.

I have previously studied how asynchronous message processing threads are implemented in Android in the Handler principle. The basic logic is

Today, I used java to simulate it to deepen my impression. The following class diagram is exported using tools. It is not formal, but we can roughly see the relationship between classes.

Message: Message <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> public class Message { public int what; public Object obj; public Handler target;}

Logoff class: this class is used to change a common thread to an asynchronous message loop class and maintain a message queue. Each thread has only logoff objects and is closed by threads. Each thread has its own copy.

public class Looper {    private MessageQueue queue;    private static final ThreadLocal
  
    sThreadLocal = new ThreadLocal
   
    ();    public Looper() {        queue = new MessageQueue();    }    public static void prepare(){        if (sThreadLocal.get() != null) {            throw new RuntimeException(Only one Looper can be created per thread);        }        sThreadLocal.set(new Looper());    }    public static Looper myLooper() {        return sThreadLocal.get();    }    public static MessageQueue myQueue() {        return myLooper().queue;    }    public static void loop(){        while(true){            Message msg = myQueue().deQueueMessage();            if (msg == null) {                continue;            }else {                msg.target.dispatchMessage(msg);            }        }    }}
   
  

MessageQueue class: Message Queue, which extracts the Message from the queue according to the first-in-first-out principle.

public class MessageQueue {    private Queue
  
    queue = new LinkedList
   
    ();    public synchronized void enqueueMessage(Message msg){        queue.offer(msg);    }    public synchronized Message deQueueMessage(){        if (queue.isEmpty()) {            return null;        }        return queue.poll();    }   }
   
  

Handler class: Generally, the queue is not directly operated, and a Message object is added to the Message Queue through handler. In addition, the handlerMessage method is exposed to allow programmers to rewrite the method for their own processing purposes.

public class Handler {    private MessageQueue queue;    public Handler(){        queue = Looper.myQueue();    }    public void sendMessage(Message msg){        msg.target = this;        queue.enqueueMessage(msg);    }    public void dispatchMessage(Message msg) {        handleMessage(msg);    }    public void handleMessage(Message msg){}}

Main class: the startup class for running the program.

public class Main {    public static void main(String[] args) {        Looper.prepare();        TestInterface test = new Test();        test.onCreate();        Looper.loop();    }}

TestInfo interface: standardizes an interface for testing

public interface TestInterface {    void onCreate();}

Test class: the only class exposed that requires the programmer to fill in the Code. In a timer, we send a message every second to the main thread and display it.

public class Test implements TestInterface{    private static SimpleDateFormat sdf=new SimpleDateFormat(HH:mm:ss);    private Handler handler = new Handler(){        public void handleMessage(Message msg) {            if (msg.what == 1) {                System.out.println(handler---> + (String)msg.obj);            }        };    };    @Override    public void onCreate() {        new Timer().schedule(new TimerTask() {            @Override            public void run() {                Message msg = new Message();                msg.what = 1;                msg.obj = test + sdf.format(new Date());                handler.sendMessage(msg);            }        }, 0,1000);    }}

The test results are as follows:

Handler-> test21: 32: 43
Handler-> test21: 32: 44
Handler-> test21: 32: 45
Handler-> test21: 32: 46
Handler-> test21: 32: 47
Handler-> test21: 32: 48
Handler-> test21: 32: 49
.......

 

Related Article

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.