Android Development Practice: Customizing worker threads with Message loops (Looper)

Source: Internet
Author: User

The previous article mentions that the UI thread of an Android system is a thread with a message loop (Looper) mechanism, while Android also provides a Handlerthread class that encapsulates a message loop (Looper) that can bind handler () objects, A message is sent to the thread through the SendMessage () function of handler, and the message received by the thread is processed through the handlemessage () function. In this case, this article uses the underlying Java class library to implement a thread with a message loop (Looper) to help beginners understand how such a Looper works.


1. First, we complete a simple threading framework.

public class looperthread {    private volatile boolean  mislooperquit = false;    private thread mthread;               public void start ()  {         if ( mThread != null )  {             return;        }         mIsLooperQuit = false;         mthread = new thread (mlooperrunnable);         mthread.start ();     }    public void stop ()  {        if ( mThread == null )  {             return;        }         mIsLooperQuit = true;         mthread = null;    }    protected runnable  Mlooperrunnable = new runnable ()  {        @ Override        public void run ()  {             while ( !mIsLooperQuit )  {             }        }     };}


As shown in the code above, the Mlooperrunnable.run () loop executes the thread task, and Mislooperquit is the condition for the thread to exit the loop. Next, we'll add the sending and handling code for the message.


2. Add message sending and processing code for thread looping


(1) Define message structure, create message queue


public class Looperthread {private queue<message> mmessagequeue = new linkedlist<message> ();    public static class Message {int; }        }


(2) Creating mutexes and condition variables


public class Looperthread {private Lock MLock = new Reentrantlock ();       Private Condition mcondition = Mlock.newcondition (); }


(3) Create a function to send a message


Send message, called by external other module, send message to thread public void sendMessage (Message message) {if (Mthread = = null) {return;    } mlock.lock (); Mmessagequeue.add (message);        Add message to Message Queue mcondition.signal (); Notifies the thread loop that there is a message coming, please immediately handle mlock.unlock ();}


(4) Creating a function to process messages


Processes the message, called by the thread inside the public void handlemessage (Message message) {//here can be tuned back to listener through a callback}


(5) Parsing messages in the Mlooperrunnable.run () loop


Protected runnable mlooperrunnable = new runnable ()  {    @ Override    public void run ()  {                 while ( !mIsLooperQuit )  {                 mlock.lock ();             Message message = null;                 try {                 while ( !mIsLooperQuit  && mmessagequeue.isempty ()  )  {                     mcondition.await ();  //sleep if no message arrives                 }                  message = mmessagequeue.poll ();             }             catch  (interruptedexception e)  {                 e.printstacktrace ();             }             finally {                 mlock.unlock ();             }                           handlemessage (message );        }                 };}


(6) Modify the thread's stop () function to wake the dormant message loop

public void Stop () {if (Mthread = = null) {return;    } Mislooperquit = true;        Mlock.lock ();    Mcondition.signal ();        Mlock.unlock ();    Mmessagequeue.clear (); Mthread = null;}


Here, a basic thread class package with message loop is completed, I believe you should write this code in the process, understand how the system realizes the message loop. Complete code see the last attachment of the post, have any questions welcome message or letter [email protected] exchange.


This article is from the "Shadow Three People" blog, please be sure to keep this source http://ticktick.blog.51cto.com/823160/1565272

Android Development Practice: Customizing worker threads with Message loops (Looper)

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.