Android asynchronous mechanism 1: Use Thread + Handler to implement non-UI Thread update UI interface, androidui
Overview: Every Android application runs in a dalvik virtual machine process. When a process starts, a main thread (MainThread) is started. The main thread is responsible for processing ui-related events, therefore, the main thread is often called the UI thread. Because Android uses a single-threaded UI model, you can only operate the UI elements in the main thread. If you operate the UI directly in a non-UI thread, an error is returned:
CalledFromWrongThreadException only the original thread that created a view hierarchy can touch its views
.
Android provides a message loop mechanism. We can use this mechanism to implement inter-thread communication. Then, we can send messages to the UI thread in a non-UI thread, and finally let the Ui thread perform ui operations.
For operations and IO operations that require a large amount of computing, we need to open a new thread to handle these heavy tasks to avoid blocking the ui thread.
Example: The following example shows how to use Thread + Handler to send a message to the UI Thread to update a message in a non-UI Thread.
ThradHandlerActivity. java:
Package com. lc. androidasyntask; import org. apache. http. httpResponse; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpClient; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; 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. imageView; import android. widget. toast; public class ThreadHandlerActivity extends Activity {private static final int MSG_SUCCESS = 0; // ID of the image retrieved: private static final int MSG_FAILURE = 1; // identify the failed image retrieval: private ImageView mImageView; private Button mButton; private Thread mThread; private Handler mHandler = New Handler () {public void handleMessage (Message msg) {// This method runs switch (msg. what) {case MSG_SUCCESS: mImageView. setImageBitmap (Bitmap) msg. obj); // imageview displays the logo Toast obtained from the network. makeText (getApplication (), getApplication (). getString (R. string. get_pic_success), Toast. LENGTH_LONG ). show (); break; case MSG_FAILURE: Toast. makeText (getApplication (), getApplication (). getString (R. string. get_pic_fail Ure), Toast. LENGTH_LONG ). show (); break ;}}; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); mImageView = (ImageView) findViewById (R. id. imageView); // display the image's ImageView mButton = (Button) findViewById (R. id. button); mButton. setOnClickListener (new OnClickListener () {public void onClick (View v) {if (mThread = null) {mThr Ead = new Thread (runnable); mThread. start (); // thread start} else {Toast. makeText (getApplication (), getApplication (). getString (R. string. thread_started), Toast. LENGTH_LONG ). show () ;}}) ;}runnable Runnable = new runnable () {public void run () {// run () run HttpClient httpClient = new DefaultHttpClient (); HttpGet httpGet = new HttpGet ("http://csdnimg.cn/www/images/csdnindex_logo.gif"); // get the l of csdn in the new thread Ogo final Bitmap bitmap; try {HttpResponse httpResponse = httpClient.exe cute (httpGet); bitmap = BitmapFactory. decodeStream (httpResponse. getEntity (). getContent ();} catch (Exception e) {mHandler. obtainMessage (MSG_FAILURE ). sendToTarget (); // failed to get the image return;} // The image is obtained successfully, and the MSG_SUCCESS ID and bitmap object mHandler are sent to the ui thread. obtainMessage (MSG_SUCCESS, bitmap ). sendToTarget (); // mImageView. setImageBitmap (bm); // error! You cannot operate the ui element in a non-ui thread // mImageView. post (new Runnable () {// another more concise method for sending messages to the ui thread. //// @ Override // public void run () {// run () method will be executed in the ui thread // mImageView. setImageBitmap (bm );//}//});}};}
Main. xml file:
<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: orientation = "vertical"> <Button android: id = "@ + id/button" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "get image"> </Button> <ImageView android: id = "@ + id/imageView" android: layout_width = "wrap_content" android: layout_height = "wrap_content"/> </LinearLayout>
Strings. xml file:
<string name="thread_started">Thread started</string> <string name="get_pic_success">Get pic success</string> <string name="get_pic_failure">Get pic failure</string>
Add the following network access permissions to the configuration file:
<! -- Do not forget to set Network Access Permissions --> <uses-permission android: name = "android. permission. INTERNET"/>
Set "com. lc. androidasyntask. ThreadHandlerActivity" to the startup page.
The result is as follows:
In this case, we use Handler and Thread to notify handler in the Thread execution structure and set the image in handler.