MessageHandler mechanism 1 in Android

Source: Internet
Author: User

 

The general idea is that two (multiple) threads share a storage area, and they operate this memory concurrently.

 

The following is a simulation program that I initially wrote. If you need it, contact me QQ402320131 ~ :

 

Here, only Hander, HandlerThread, and Looper2 are attached.

 

Package com. zte. liu;

 

Public class Handler {

 

Private Looper2 logoff = null;

 

Public Handler (Looper2 looper ){

This. logoff = logoff;

}

 

Public Message obtainMessage (){

Return new Message (this );

}

 

Public Message obtainMessage (int id ){

Return new Message (id, this );

}

 

Public void dispatchMsg (Message msg ){

HandleMessage (msg );

}

 

Public Looper2 getLooper (){

Return logoff;

}

 

Public void handleMessage (Message msg) {// Hook Function

System. out. println (msg. getId ());

}

}

 

 

 

 

Public class HandlerThread implements Runnable {

 

Public void run (){

Looper2.prepare ();

Looper2.loop ();

}

 

}

 

 

 

 

 

Package com. zte. liu;

 

Public class Looper2 {

 

Private static Looper2 loop = null;

Private MessageQueue <Message> mQueue;

Private Looper2 (){

MQueue = new MessageQueue ();

}

 

Public static void prepare (){

If (logoff = null ){

Loop = new Looper2 ();

} Www.2cto.com

}

 

Public static Looper2 myloop (){

Prepare ();

Return logoff;

}

 

Public MessageQueue <Message> getQueue (){

Return mQueue;

}

 

Public static final void loop (){

System. out. println ("loop begin ...");

Looper2 loop = myloop ();

MessageQueue <Message> queue = logoff. mQueue;

If (logoff = null ){

Return;

}

While (true ){

System. out. println ("---- queue size =" + queue. size ());

Try {

Thread. sleep (1000 );

} Catch (InterruptedException e ){

E. printStackTrace ();

}

Message msg = (Message) queue. next ();

If (msg! = Null ){

If (msg. getHandler () = null) return;

Else {

Msg. getHandler (). dispatchMsg (msg );

Message. recycle (msg );

}

}

}

}

}

From: liuyangsyouxiang Column

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.