Multithreaded programming in Android (ii) The principle of handler (attached source)

Source: Internet
Author: User

The principle of handler in Android

I. Principle of handler:

The relationship between 1.Handler, Looper and MessageQueue.

(1). Handler class: sends a message to the MessageQueue message queue, receives the message returned by the Looper, and processes it.

(2). Looper class: a container that stores message queues. Responsible for receiving handler sent messages, and directly to the message back to handler himself.

(3). MessageQueue class: stores messages.

2. Relationship:

(1). When you create a handler object, it is bound to the default thread (the UI thread), and there is a message queue in the thread.

privatenew Handler() {    publicvoidhandleMessage(android.os.Message msg) {        "主线程 Thread UI:" + Thread.currentThread().getId());        mView.setText("111");    

(2). If you are opening a new child thread, when you manipulate handler in that thread, create a Looper object yourself to find the appropriate message queue. In other words, handle and looper are interrelated.

 PackageCom.chengdong.su.handlerdemo;Importandroid.app.Activity;ImportAndroid.app.ActionBar;ImportAndroid.app.Fragment;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.util.SparseArray;ImportAndroid.view.LayoutInflater;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast;ImportAndroid.os.Build;/** * * @author SCD * */ Public  class thridactivity extends Activity {    PrivateString TAG = GetClass (). Getsimplename ();PrivateTextView MView;PrivateMyThread Mthread;/** * Create a default handler * /    PrivateHandler Mhandler =NewHandler () { Public void Handlemessage(Android.os.Message msg) {LOG.D (TAG,"-------UI Thread:"+ Thread.CurrentThread (). GetId ()); Mview.settext ("Hello");    }; };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Init (); Mthread =NewMyThread (); Mthread.start ();Try{Mthread.sleep ( -); }Catch(Interruptedexception e)        {E.printstacktrace (); }//Sub-threadsMThread.myHandler.sendEmptyMessage (0);//Main threadMhandler.sendemptymessage (1); }Private void Init() {MView = (TextView) Findviewbyid (R.ID.TEXTVIEW1); }/** * Custom Thread * * @author SCD * */     Public  class MyThread extends Thread {         PublicHandler MyHandler;@Override         Public void Run() {looper.prepare (); MyHandler =NewHandler () {@Override                 Public void Handlemessage(Message msg) {Super. Handlemessage (msg); LOG.D (TAG,"------>thread:"+ Thread.CurrentThread (). GetId ()); System.out.println ("---child thread----"); }            };//Loop processing messagesLooper.loop (); }    }}

However, using the above method will lead to multi-threaded concurrency caused by the null pointer problem, in order to avoid this problem, Google has encapsulated a very useful class: Handlerthread class.

3.HandlerThread class:

(1). Resolves null pointer problems caused by multithreading concurrency.
The use code for Handlerthread is as follows:

 PackageCom.chengdong.su.handlerdemo;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.HandlerThread;ImportAndroid.os.Message;ImportAndroid.util.Log;/** * * @author SCD * */ Public  class fouractivity extends Activity {    PrivateString TAG = GetClass (). Getsimplename ();PrivateString Mname ="Handlerthread";PrivateHandlerthread Mthread;PrivateHandler Mhandler;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//Package classMthread =NewHandlerthread (Mname);//Open threadMthread.start ();//Way One: handler is on a child threadMhandler =NewHandler (Mthread.getlooper ()) {@Override             Public void Handlemessage(Message msg) {Super. Handlemessage (msg); LOG.D (TAG,"---child thread----handlerthread:"+ Thread.CurrentThread (). GetId ()); }        };//Mode two: handler is in the main threadMhandler =NewHandler () {@Override             Public void Handlemessage(Message msg) {Super. Handlemessage (msg); LOG.D (TAG,"---main thread UI----handlerthread:"+ Thread.CurrentThread (). GetId ());        }        }; Mhandler.sendemptymessage (0); LOG.D (TAG,"---main thread----uithread:"+ Thread.CurrentThread (). GetId ()); }}

Note: The Mhandler in mode one is run in a sub-thread, which can handle time-consuming asynchronous tasks, send messages, process messages, and so on in the handler.

(2). Communication between the main thread and child threads in Android:

A: Strand Cheng sent to the main thread message: Let the main thread update the UI interface
B: The main line Cheng to the child thread message: Let the child thread do the corresponding logical processing.
The code is as follows:

 PackageCom.chengdong.su.handlerdemo;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.HandlerThread;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;/** * Send messages to each other between the main thread and the child threads for communication * * @author SCD * */ Public  class fiveactivity extends Activity  implements  Onclicklistener {    PrivateString TAG = GetClass (). Getsimplename ();PrivateString Mname ="Handlerthread";//Initialize the handler of the main thread    PrivateHandler Mhandler =NewHandler () { Public void Handlemessage(Message msg) {Message message =NewMessage ();//Mainline Cheng to child thread messagesmthreadhandler.sendmessagedelayed (Message, +); LOG.D (TAG,"--------> Mainline Cheng to Child thread messages");    }; };//Sub-threading Object    PrivateHandlerthread Mthread;//Sub-thread handler    PrivateHandler Mthreadhandler;PrivateButton MButton1;PrivateButton MButton2;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);    Init (); }/** * Init the View * *    Private void Init() {MButton1 = (Button) Findviewbyid (R.id.button1);        MButton2 = (Button) Findviewbyid (R.id.button2); Mbutton1.setonclicklistener ( This); Mbutton2.setonclicklistener ( This);//Initialize the handler of the child threadMthread =NewHandlerthread (Mname); Mthread.start ();//Initialize the handler in the child threadMthreadhandler =NewHandler (Mthread.getlooper ()) {@Override             Public void Handlemessage(Message msg) {Message message =NewMessage (); mhandler.sendmessagedelayed (Message, +); LOG.D (TAG,"--------> Strand Cheng to the main thread message");        }        }; LOG.D (TAG,"------->init main thread"); }@Override     Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.button1: {//main thread send messageMhandler.sendemptymessage (0); Break; } CaseR.id.button2: {//Cancel messageMhandler.removemessages (0); Break; }default: Break; }    }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Multithreaded programming in Android (ii) The principle of handler (attached source)

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.