I. Basic Concepts
This is often the case when using a mobile phone: for example, when we separate the download method into an Activity during download, other activities do not respond during download, at this time, the entire mobile phone is in the active state, and Handler is used to solve this problem.
This means that when the download is placed in a separate thread, the thread of the Activity will not be affected when the thread is executed.
Ii. Usage
Call the post method of handler to implement thread operations.
The simplest example of Handler:
XML file:
Java code
<Span style = "font-size: x-small;"> <? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
Android: weightSum = "1">
<Button
Android: id = "@ + id/start"
Android: text = "@ string/opt_start"
Android: layout_height = "wrap_content"
Android: layout_weight = "0.38"
Android: layout_width = "202dp"/>
<Button
Android: layout_height = "wrap_content"
Android: id = "@ + id/end"
Android: text = "@ string/opt_end"
Android: layout_weight = "0.38"
Android: layout_width = "202dp">
</Button>
</LinearLayout>
</Span>
Handler file:
Java code
<Span style = "font-size: x-small;"> package com. hadler;
Import android. accounts. Account;
Import android. accounts. OnAccountsUpdateListener;
Import android. app. Activity;
Import android. content. Intent;
Import android. OS. Bundle;
Import android. OS. Handler;
Import android. text. style. UpdateAppearance;
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 start;
Private Button end;
OnClickListener start_listen = null;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Start = (Button) findViewById (R. id. start );
End = (Button) findViewById (R. id. end );
Start_listen = (new OnClickListener (){
@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
// Call the post method of handler and add the thread object to be executed to the queue
Handler. post (updateThread );
}
});
Start. setOnClickListener (start_listen );
OnClickListener end_listen = (new OnClickListener (){
@ Override
Public void onClick (View arg0 ){
// TODO Auto-generated method stub
Handler. removeCallbacks (updateThread );
}
});
End. setOnClickListener (end_listen );
}
// Create a Handler object
Handler handler = new Handler ();
// Thread class that implements the Runnable interface and writes the operations to be executed in the run Method
Runnable updateThread = new Runnable (){
@ Override
Public void run (){
// TODO Auto-generated method stub
System. out. println ("UpdateThread ");
// Execute the postDelayed or post method within the run method.
Handler. postDelayed (updateThread, 3000 );
}
};
} </Span>
In this example, an UpdateThread statement is printed in LogCat every three seconds.
That is, the code segment completed by calling a new process, that is, asynchronous processing, does not affect the current Acvtivity.
3. Update the progress bar using handler
Next, let's look at an example to update the progress bar.
Java code
<Span style = "font-size: x-small;"> package mars. barhandler;
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 TestBarHandler extends Activity {
/** Called when the activity is first created .*/
// Declare control variables
ProgressBar bar = null;
Button startButton = null;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Obtain the object representing the Control Based on the Control ID and set the listener for the button
Bar = (ProgressBar) findViewById (R. id. bar );
StartButton = (Button) findViewById (R. id. startButton );
StartButton. setOnClickListener (new ButtonListener ());
}
// When you click startButton, The onClick method of ButtonListener is executed.
Class ButtonListener implements OnClickListener {
@ Override
// Anonymous internal class
Public void onClick (View v ){
// TODO Auto-generated method stub
// Set the progress bar to visible
Bar. setVisibility (View. VISIBLE );
// Add the thread object updateThread to the Message Queue immediately. The execution thread is the run method.
UpdateBarHandler. post (updateThread );
}
}
// Use an anonymous internal class to rewrite the handleMessage method in the Handler.
Handler updateBarHandler = new Handler (){
@ Override
Public void handleMessage (Message msg ){
// Add msg that has been pushed into the message queue to the thread queue
Bar. setProgress (msg. arg1) // set the current value of the progress bar <br> Bundle bundle = msg. getData ();
UpdateBarHandler. post (updateThread );
System. out. println ("test ---->" + bundle. getString ("test "));
}
};
// Thread class, which is declared using an anonymous internal class
Runnable updateThread = new Runnable (){
Int I = 0;
@ Override
Public void run (){
System. out. println ("Begin Thread" + I );
I = I + 10;
// Get a Message object. The Message class is provided by the Android operating system.
Message msg = updateBarHandler. obtainMessage ();
// Set the arg1 parameter value of the msg object to I and use the two member variables arg1 and arg2 to transmit messages. The advantage is that the system performance consumption is low.
Msg. arg1 = I;
Bundle bundle = new Bundle ();
Bundle. putString ("test", "test bundle ");
Msg. setData (bundle );
Try {
// Set the current thread to sleep for 1 second
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
// Add the msg object to the Message Queue
When (I> 100 ){
// If the I value is 100, the thread object will be removed from handler.
UpdateBarHandler. removeCallbacks (updateThread );
System. out. println (">>>>> ");
} Else {
// Press msg into the message queue. After being pushed, The handleMessage method above will be executed.
// Press in once every execution. The code above tells me that msg is added to the thread queue. As long as I is less than 100, this operation will be continuously circulating.
UpdateBarHandler. sendMessage (msg );
System. out. println ("<");
}
}
};
Class MyThread extends Thread {
Public void run (){
}
}
} </Span>