In Android asynchronous processing 1: Using Thread + Handler to update the UI of a non-UI Thread.
Overview: AsyncTask is an auxiliary class launched after Android SDK 1.5 to facilitate the interaction between background threads and UI threads. The internal implementation of AsyncTask is a thread pool. Each background task is submitted to the thread pool for thread execution, then call the callback function using Thread + Handler (for details about the principle, see Android asynchronous processing 4: AsyncTask implementation principle).
AsyncTask abstracts the five statuses of background thread running, namely: 1. Prepare for running; 2. running in the background; 3. Updating progress; 4. Completing background tasks, 5. Cancel the task. For these five phases, AsyncTask provides five callback functions:
1. Prepare to run: onPreExecute (). The callback function is called by the UI thread immediately after the task is executed. This step is usually used to create a task and display the progress bar on the user interface (UI.
2. running in the background: doInBackground (Params...). The callback function is called immediately after the onPreExecute () method is executed by the background thread. Generally, time-consuming background computing is executed here. The calculation result must be returned by this function and passed to onPostExecute. You can also use publishProgress (Progress...) in this function to publish one or more progress units (unitsof Progress ). These values will be published to the UI thread in onProgressUpdate (Progress.
3. Progress Update: onProgressUpdate (Progress...). This function is called by the UI thread after the publishProgress (Progress...) method is called. It is generally used to dynamically display a progress bar.
4. Complete the background task: onPostExecute (Result), which is called after the background computing is complete. The result of background computing is passed as a parameter to this function.
5. cancel the task: onCancelled (). It is called when the cancel () method of AsyncTask is called.
The AsyncTask constructor has three template parameters:
1. Params: parameter type passed to the background task.
2. Progress: indicates the type of the progress unit during background computing execution. (That is, the background program has executed a few percent .)
3. Result: The type of the Result returned by the background execution.
AsyncTask does not always need to use all three types above. It is easy to identify a type that is not used. You only need to use the Void type.
Example: similar to the example in Android asynchronous processing 1: Using Thread + Handler to update the UI of a non-UI Thread, we download the csdn logo in the background, after the download is complete, it is displayed on the UI and the download progress is updated.
Download example project files
AsyncTaskActivity. java
[Java]
1. package com. zhuozhuo;
2.
3.
4. import org. apache. http. HttpResponse;
5. import org. apache. http. client. HttpClient;
6. import org. apache. http. client. methods. HttpGet;
7. import org. apache. http. impl. client. DefaultHttpClient;
8.
9. import android. app. Activity;
10. import android. graphics. Bitmap;
11. import android. graphics. BitmapFactory;
12. import android. OS. AsyncTask;
13. import android. OS. Bundle;
14. import android. view. View;
15. import android. view. View. OnClickListener;
16. import android. widget. Button;
17. import android. widget. ImageView;
18. import android. widget. ProgressBar;
19. import android. widget. Toast;
20.
21. public class AsyncTaskActivity extends Activity {
22.
23. private ImageView mImageView;
24. private Button mButton;
25. private ProgressBar mProgressBar;
26.
27. @ Override
28. public void onCreate (Bundle savedInstanceState ){
29. super. onCreate (savedInstanceState );
30. setContentView (R. layout. main );
31.
32. mImageView = (ImageView) findViewById (R. id. imageView );
33. mButton = (Button) findViewById (R. id. button );
34. mProgressBar = (ProgressBar) findViewById (R. id. progressBar );
35. mButton. setOnClickListener (new OnClickListener (){
36.
37. @ Override
38. public void onClick (View v ){
39. GetCSDNLogoTask task = new GetCSDNLogoTask ();
40. task.exe cute ("http://www.bkjia.com/uploadfile/2012/0412/20120412094410900.gif ");
41 .}
42 .});
43 .}
44.
45. class GetCSDNLogoTask extends AsyncTask <String, Integer, Bitmap> {// inherit AsyncTask
46.
47. @ Override
48. protected Bitmap doInBackground (String... params) {// process the tasks executed in the background and run them in the background thread
49. publishProgress (0); // The onProgressUpdate (Integer... progress) method will be called.
50. HttpClient hc = new DefaultHttpClient ();
51. publishProgress (30 );
52. HttpGet hg = new HttpGet (params [0]); // obtain the csdn logo
53. final Bitmap bm;
54. try {
55. HttpResponse hr = hc.exe cute (hg );
56. bm = BitmapFactory. decodeStream (hr. getEntity (). getContent ());
57.} catch (Exception e ){
58.
59. return null;
60 .}
61. publishProgress (100 );
62. // mImageView. setImageBitmap (result); the ui cannot be operated in the background thread
63. return bm;
64 .}
65.
66. protected void onProgressUpdate (Integer... progress) {// called after publishProgress is called and executed in the ui thread
67. mProgressBar. setProgress (progress [0]); // update the progress of the progress bar
68 .}
69.
70. protected void onPostExecute (Bitmap result) {// called after the background task is executed and executed in the ui thread
71. if (result! = Null ){
72. Toast. makeText (AsyncTaskActivity. this, "image retrieved successfully", Toast. LENGTH_LONG). show ();
73. mImageView. setImageBitmap (result );
74.} else {
75. Toast. makeText (AsyncTaskActivity. this, "Image Retrieval failed", Toast. LENGTH_LONG). show ();
76 .}
77 .}
78.
79. protected void onPreExecute () {// called before doInBackground (Params...) and executed in the ui thread
80. mImageView. setImageBitmap (null );
81. mProgressBar. setProgress (0); // progress bar Reset
82 .}
83.
84. protected void onCancelled () {// executed in the ui thread
85. mProgressBar. setProgress (0); // progress bar Reset
86 .}
87.
88 .}
89.
90.
91 .}
Main. xml
[Html]
1. <? Xml version = "1.0" encoding = "UTF-8"?>
2. <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
3. android: orientation = "vertical" android: layout_width = "fill_parent"
4. android: layout_height = "fill_parent">
5. <ProgressBar android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: id = "@ + id/progressBar" style = "? Android: attr/progressBarStyleHorizontal "> </ProgressBar>
6. <Button android: id = "@ + id/button" android: text = "Download image" android: layout_width = "wrap_content" android: layout_height = "wrap_content"> </Button>
7. <ImageView android: id = "@ + id/imageView" android: layout_height = "wrap_content"
8. android: layout_width = "wrap_content"/>
9. </LinearLayout>
Manifest. xml
[Html]
1. <? Xml version = "1.0" encoding = "UTF-8"?>
2. <manifest xmlns: android = "http://schemas.android.com/apk/res/android"
3. package = "com. zhuozhuo"
4. android: versionCode = "1"
5. android: versionName = "1.0" type = "codeph" text = "/codeph">
6. <uses-sdk android: minSdkVersion = "10"/>
7. <uses-permission android: name = "android. permission. INTERNET"> </uses-permission>
8. <application android: icon = "@ drawable/icon" android: label = "@ string/app_name">
9. <activity android: name = ". AsyncTaskActivity"
10. android: label = "@ string/app_name">
11. <intent-filter>
12. <action android: name = "android. intent. action. MAIN"/>
13. <category android: name = "android. intent. category. LAUNCHER"/>
14. </intent-filter>
15. </activity>
16.
17. </application>
18. </manifest>
Running result:
Process description:
1. When you click the button, create a task and input the csdn logo address (String type parameter, so the first template parameter of AsyncTask is String type)
2. the UI thread executes onPreExecute (), clears the ImageView image, and clears the progress of progrssbar.
3. The background thread executes doInBackground (). You cannot operate the ui on doInBackground () and call publishProgress (0) to update the progress. At this time, onProgressUpdate (Integer... progress bar (progress is expressed in an Integer, so the second template parameter of AsyncTask is Integer ). The function returns result (in this example, the Bitmap type is returned, so the second template parameter of AsyncTask is Bitmap ).
4. After the background task is executed, call onPostExecute (Result). The input parameter is the object returned by doInBackground.
Summary:
AsyncTask abstracts the five States of a background task and corresponds to five callback interfaces. We only need to implement these five interfaces according to different requirements (doInBackground must be implemented ), you can complete some simple background tasks. The AsyncTask method makes the code for compiling the background process and UI process interaction more concise and easier to use. However, AsyncTask also has some shortcomings. We will leave it for further discussion.
From lzc's column