Use of handler (i)
Handler Basic Concepts:
Handler is mainly used for processing asynchronous messages: When a message is sent, first enters a message queue, the function that sends the message returns immediately, and the other part takes the message out of the message queue one after the other, and then the message is sent out, that is, the sending message and receiving the message is not synchronous processing.
This mechanism is often used to handle relatively long-time operations.
Use a simple example to introduce the handler.
Example 1: There are 2 buttons (start, end) in an application, and when the Start button is clicked, a thread is executed, which outputs a string of strings in the console and executes the thread once every 3 seconds until the end button is clicked and the thread stops.
For the interface of this application:
Output for the console when executing the program:
Development steps:
1. Create a new Android app
2. Add 2 Button control labels to the layout file and set properties and values for them
3. In activity, declare the control variable and get the control object by ID
4. In activity, create a handler object
5. In activity, create a Runnable object
A) in the form of anonymous internal classes
b) The action to be performed is written in the run () method in the Runnable object
I. Print a sentence
II. Calling the Postdelayed () method of the Runnable object
6. In activity, write the listener required by the Start button and bind
A) in the OnClick () method of this listener, call handler's post () method and put the thread object that will be executed into the queue.
7. In activity, write the listener required by the end button and help set
A) in the OnClick () method of this listener, call handler's Removecallbacks () method to delete the thread object that is not executing in the queue.
b
Here's the code for the activity:
Package Android.handler;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;public class HandlerTest Extends activity {/** Called when the activity is first created. */private button Startbutton;private button Endbutton ; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Gets the control object Startbutton = (Button) Findviewbyid (R.id.startbutton) based on the ID; Endbutton = (Button) Findviewbyid (R.id.endbutton); Sets the Listener Startbutton.setonclicklistener (new Startbuttonlistener ()) for the control; Endbutton.setonclicklistener (New Endbuttonlistener ()); } class Startbuttonlistener implements Onclicklistener{public void OnClick (View v) {//Call Handler's post () method, the thread object to be executed is placed Into the queue handler.post (updatethread);} } class Endbuttonlistener implements onclicklistener{public void OnClick (View v) {//calls Handler's Removecallbacks () method to delete thread objects not executed in the queue handler.removecallbacks (updatethread);} }//Create Handler object Handler Handler = new Handler (); Create a new Thread object Runnable updatethread = new Runnable () {//The action to be performed in the run method of the write thread object, public void Run () {System.out.print ln ("Updatethread"); Call Handler's postdelayed () method//The function of this method is to put the thread object to be executed into the queue, after the time is over, run the developed thread object//The first parameter is the runnable type: The thread object to be executed//The second parameter is Lon Type G: Delay time, in milliseconds handler.postdelayed (Updatethread, 3000); } };}
The above is one of the simplest examples, and here is another example.
Example 2: An application has a progress bar and a button that, when clicked, is part of a progress bar every second.
For the application to run:
Development steps:
1. Create a new Android app
2. Add a ProgressBar and a button to the layout file and set properties and values for it
3. In activity, declare the control variable and get the control object by ID
4. Creating Thread objects
A) by anonymous inner class method
b) After writing 5, 6 steps to continue writing this thread object operation
I. Declaring the progress of a variable used to set the progress bar
II. Rewrite the thread class's Run method (), which writes the action to be performed
1. Print a string
2. Increase in the value of the progress bar
3. Get a Message Object
4. Set the value of the message object Arg1
5. Let the thread sleep for a second
6. Placing a Message object in a message queue
7. Determine that if the value of the progress bar equals 100, the thread object is removed from the queue.
5. Create a Handler object
A) different from Example 1 is that this is declared by an anonymous inner class, and Example 1 is a direct new object
b) Overriding the Handlermessage (Message msg) method of the Handler object
I. This method passes in a Message object, which is the information object, which first sets the progress of the progress bar (the value is a member variable arg1 within the Messag object).
II. Put the thread object to be executed into the queue
6. Write the listener that the button needs, and bind
A) Set the progress bar to display state
b) Put the thread object that will be executed into the queue
Here's the code for the activity:
Package Android.handler;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.os.message;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button Import Android.widget.progressbar;public class Progressbarhandlertest extends activity {/** called when the activity is first created. */private ProgressBar progressbar;private Button Startbutton; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); ProgressBar = (ProgressBar) Findviewbyid (R.id.progressbar); Startbutton = (Button) Findviewbyid (R.id.startbutton); Startbutton.setonclicklistener (New Progressbaronclicklistener ()); } class Progressbaronclicklistener implements Onclicklistener{public void OnClick (View v) {//sets the progress bar to a visible state ProgressBar. Setvisibility (view.visible); Updatebarhandler.post (Updatethread);} }//Using anonymous inner classesHandler handlermessage () method Handler Updatebarhandler = new Handler () {@Overridepublic void Handlemessage (Message ms g) {progressbar.setprogress (MSG.ARG1); Updatebarhandler.post (updatethread);//The thread that will be executed is put into the queue}}; The thread class, which is declared using an anonymous inner class Runnable updatethread = new Runnable () {int i = 0;public void run () {//TODO auto-generated m Ethod stubSystem.out.println ("Begin Thread"); i+=10;//get a Message object, the message class is the message msg provided by the Android system Updatebarhandler.obtainmessage ();//The value of the ARG1 parameter of the message object is set to Imsg.arg1 = i;//is passed with the two member variables arg1, ARG2, with the advantage that the system performance is less expensive try{ Thread.Sleep (1000);//Let the current thread hibernate 1000 milliseconds}catch (Interruptedexception ex) {ex.printstacktrace ();} Add Message object to Message Queue Updatebarhandler.sendmessage (msg);//If the value of I equals 100if (i = = 100) {// Remove the thread object from the queue updatebarhandler.removecallbacks (Updatethread);}} };}
Have the opportunity to explore more, more exchanges and exchanges!
Use of Android handler (i)