Android Handler Details + example

Source: Internet
Author: User

This article mainly describes the use of handler in Android, handler with multi-threading, Message Queuing is very close, in the normal development of the actual program is more common. This article is divided into 4 simple examples.

Handler Use Example 1
This example is the simplest introduction to handler used, which is to bind handler to the thread it is creating.
This experiment completes the function is: Click the Start button, the program will start to start the thread, and the thread program completes after the delay 1s will continue to start the thread, each time the thread's run function completes the interface output Nupdatethread ... Text, keep running, when the end button is clicked, the thread stops, and if you continue clicking Start, the text starts to output again. The code is as follows:

Mainactivity.java

Package com.example.handler1; Import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.view.Menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import  Android.widget.TextView;    public class Mainactivity extends Activity {private TextView text_view = null;    Private Button start = null;    Private Button end = null;    The first thing to do when using Handler is to create a Handler Handler Handler = new Handler ();  To handle multithreading with handler, you can use the Runnable interface, which first defines the interface//thread that runs the interface's run function Runnable update_thread = new Runnable () {public            void Run () {//thread outputs "Updatethread ..." text each time it executes, and the Append function of//textview is similar to the append in Qt and does not overwrite the previous            The content, only QT in the append default is the automatic line wrapping mode text_view.append ("\nupdatethread ...");        Delay 1s after the thread is added to the thread queue handler.postdelayed (update_thread, 1000);    }    }; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (SAVedinstancestate);        Setcontentview (R.layout.activity_main);        Text_view = (TextView) Findviewbyid (R.id.text_view);        Start = (Button) Findviewbyid (R.id.start);        Start.setonclicklistener (New Startclicklistener ());        End = (Button) Findviewbyid (r.id.end);    End.setonclicklistener (New Endclicklistener ());  } Private class Startclicklistener implements Onclicklistener {public void OnClick (View v) {//        TODO auto-generated Method Stub//thread interface is immediately sent to thread queue handler.post (update_thread);  }} Private class Endclicklistener implements Onclicklistener {public void OnClick (View V) {//TODO auto-generated Method Stub//remove interface from thread queue Handler.removecallbacks (update_thr        EAD); }} @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.activity_ma        in, menu);    return true;  }}
Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation= "vertical" >       <textview        android:id= "@+id/text_view"        android:layout_ Width= "Fill_parent"        android:layout_height= "200dip"        android:text= "@string/hello_world"        tools: Context= ". Mainactivity "/>    <button         android:id=" @+id/start        "android:layout_width=" Fill_parent " android:layout_height= "Wrap_content"        android:text= "@string/start"        />    <button         android : id= "@+id/end"        android:layout_width= "fill_parent"        android:layout_height= "Wrap_content"        android: text= "@string/end"        />  </LinearLayout>  

Handler Use Example 2
This example is a little more complicated than the example just now. Because this example uses the handler Message Queuing mechanism, that is, sending a message through a thread in handler to the message queue using the SendMessage method, the message sent can of course be used to pass parameters. Using Handlemessage to process messages in handler, the processing method is to get the message parameters in the message queue and use these parameters to accomplish some other functions.
This experiment realizes that when the Start button is pressed, a thread is started and bound to handler, which sends a message with the parameter to the handler queue, the other end of the message queue gets the message, and the progress bar is updated with the parameters of the message.

Mainactivity.java

Package com.example.handler2; Import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.os.Message;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button; Import Android.widget.ProgressBar;    public class Mainactivity extends Activity {private ProgressBar progress_bar = null;    Private Button start = null;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Progress_bar = (ProgressBar) Findviewbyid (R.id.progress_bar);        Start = (Button) Findviewbyid (R.id.start);    Start.setonclicklistener (New Startonclicklistenr ()); } Private class Startonclicklistenr implements Onclicklistener {public void OnClick (View v) {//            TODO auto-generated Method Stub//Let Progress bar show progress_bar.setvisibility (view.visible); Adding a thread to the HANdler thread Queue update_progress_bar.post (update_thread); }}//Create a Handler, internally complete processing message method Handler Update_progress_bar = new Handler () {@Override public voi            D handlemessage (Message msg) {//TODO auto-generated Method Stub//super.handlemessage (msg);            Show progress bar progress_bar.setprogress (MSG.ARG1);        Re-add the process to the process queue update_progress_bar.post (update_thread);        }};//does not add this semicolon and cannot be automatically added code Runnable update_thread = new Runnable () {int i = 0;            public void Run () {//TODO auto-generated Method Stub i + = 10;            Get a message structure first MSG = Update_progress_bar.obtainmessage ();            Assigning a value to the ARG1 parameter of the message structure MSG.ARG1 = i;            The Try+catch in delay 1s,java is used for troubleshooting the try {thread.sleep (1000); } catch (Interruptedexception e) {//Todo:handle exception E.printstacktraCE ();            }//Send message to Message Queue Update_progress_bar.sendmessage (msg);        if (i = = 100)//Remove the thread from the thread queue update_progress_bar.removecallbacks (update_thread);    }           };         @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.activity_main, menu);    return true; }}

Activity_main.xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent " >       <button         android:id= "@+id/start"        android:layout_width= "fill_parent"        android:layout_ height= "Wrap_content"        android:layout_alignparentbottom= "true"        android:text= "@string/start"        />    <progressbar         android:id= "@+id/progress_bar"        android:layout_width= "Fill_parent"        Android : layout_height= "100dip"        android:layout_alignparenttop= "true"        style= "? android:attr/ Progressbarstylehorizontal "        android:visibility=" Gone "        />  

Handler Use Example 3
The above 2 examples on the surface see handler using the Post method to start the Runnbale, actually the thread that started is the same thread as the activity thread, because it just runs the thread's Run method, not the Start method. The goal of the Mars Teacher Experiment 3 is to verify that the Post method using only handler is on the same thread.
The Experiment Prints 2 information about this thread in the OnCreate function of the main activtiy, creates a handler and binds it to a thread, prints the thread's information in the run method of the threads, and observes whether the information for the 2 is the same.

The results are as follows:
Note that these 2 threads are indeed the same thread, and you can see that the text in the main interface is about 10s before it appears because the statement Setcontentview (R.layout.activity_main) is placed behind the handler post startup statement. The handler bound thread also has a delay of 10s, so it proves that only the same thread will be present.

The program's main code and comments are as follows:

Mainactivity.java

Package Com.example.handler3;  Import Android.app.activity;import android.os.bundle;import android.os.handler;import android.view.Menu;    public class Mainactivity extends Activity {//Create a new Handler private Handler Handler = new Handler ();        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Load the runnable into the handler thread queue//Handler.post (R);        Thread t = new Thread (r);        T.start ();        Setcontentview (R.layout.activity_main);        Print activtiy Thread information System.out.println ("activity_id---->" +thread.currentthread (). GetId ());    System.out.println ("activity_name---->" +thread.currentthread (). GetName ());            } Runnable r = new Runnable () {public void run () {//TODO auto-generated method stub            Print new Thread Information System.out.println ("handler_id---->" +thread.currentthread (). GetId ()); System.out.println ("handler_name---->" +thread.curreNtthread (). GetName ());            Delay 10s, in order to observe the contents of the main interface in the time of the try {Thread.Sleep (10000);            } catch (Interruptedexception e) {//Todo:handle exception e.printstacktrace ();    }        }    };         @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.activity_main, menu);    return true;  }}

If you put the statement:
Handler.post (R);
Into:
Thread t = new Thread (r);
T.start ();
The other is unchanged, the main interface content is displayed immediately when the program runs, and the system output is as follows:
These 2 indicate that such a bound thread is not the same thread as the activity thread on which it resides.

Handler Use Example 4
This example will learn how to start a thread without using runnable, but instead use the Handlerthread looper to construct a handler and then handler to get the message, pass the data, and process the message yourself. This is, of course, done in another thread.
A simple integer passed in the message structure can take its arguments arg1 and arg2, or pass some small other data, and it can use its object, which can be any object. When it is necessary to transfer larger data, you can use the SetData method of the message, which needs to pass the parameters of a bundle. A map of a key-value pair is stored in the bundle, except that its key-value type and data type are relatively fixed.

The program's main code and comments are as follows:

Mainactivity.java

Package com.example.handler4; Import Android.app.activity;import android.os.bundle;import android.os.handler;import android.os.HandlerThread;  Import Android.os.looper;import Android.os.message;import Android.view.Menu; public class Mainactivity extends Activity {@Override public void onCreate (Bundle savedinstancestate) {su        Per.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        System.out.println ("activity_id---->" +thread.currentthread (). GetId ());        Creates a new Handerthread object that implements the function of using looper to process Message Queuing handlerthread handler_thread = new Handlerthread ("Handler_thread");        Handler_thread.start ();         The MyHandler class is a class of its own inheritance, where it is initialized with Hand_thread's looper myhandler my_handler = new MyHandler (Handler_thread.getlooper ());        Get a message msg message msg = My_handler.obtainmessage ();        Using the bundle to save the data, the bundle is stored in a key-value pair of map, but its key value type and data type is relatively fixed bundle B = new bundle ();        B.putstring ("Whether", "Sunny Day"); B.Putint ("Temperature", 34);      Msg.setdata (b);    Send msg to its own handler, here refers to the My_handler, call the handler Handlemessage method to handle the mug Msg.sendtotarget (); } class MyHandler extends Handler {//null constructor public MyHandler () {}//function passed with looper type parameter, Looper is a message pump that is constantly looping through messages and processing from message queues, so//each message queue has a Looper because Looper is the class public myhandler for Message Queuing and message loops that are already encapsulated (Looper loop        ER) {//Call the constructor of the parent class super (Looper);            } @Override public void Handlemessage (Message msg) {//TODO auto-generated method stub            System.out.println ("handler_id---->" +thread.currentthread (). GetId ());            System.out.println ("handler_name---->" +thread.currentthread (). GetId ());            The bundle data in the message is taken out bundle B = Msg.getdata ();            String whether = b.getstring ("whether");            int temperature = B.getint ("Temperature"); System.out.println ("whether=" +whether+ ", temperature=" +temperature); }} @Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.activity_ma        in, menu);    return true;  }}

Summarize:
Handler in Android can be used to complete asynchronous messages, that is, sending messages and receiving messages are independent of each other and can be run concurrently. In Example 1 and Example 2, actually the thread used in handler is in the same main thread as the activity in which it resides, because the runnable interface that is called in handler is the run function that runs the interface directly, not the start function. Example 3 specifically compares these 2 cases. Example 4 learns how to work with messages in a new thread.

Android Handler Details + example

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.