Android asynchronously updates the UI ---- AsyncTask

Source: Internet
Author: User

Android asynchronous UI update ---- handler + thread we use handler as a bridge between thread and UI thread. android itself also provides us with an asynchronous update method AsyncTask, asyncTask is lighter than hander. AsyncTask is provided in Android1.5. It makes it easier to create long-running tasks that need to interact with the user interface. The advantages of AsyncTask are as follows: • The thread overhead is high. If each task needs to create a thread, the efficiency of the application process is much lower. • The thread cannot be managed, after an anonymous thread is created and started, it is not controlled by the program. If many requests are sent, many threads are started and the system is overwhelmed. • As we can see earlier, handler must be introduced for UI updates in the new thread, which makes the Code look very bloated. Of course, AsyncTask does not have any disadvantages. This is detailed in the next chapter. 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 (). When the cancel () method of AsyncTask is called, the constructor of AsyncTask has three template parameters: 1. params, the 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.

Package com. example. thread; 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 com. example. test. r; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. asyncTask; import android. OS. bundle; import android Oid. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. imageView; import android. widget. progressBar; import android. widget. toast; public class AsyncTaskActivity extends Activity {private ImageView mImageView; private Button mButton; private ProgressBar mProgressBar; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (s AvedInstanceState); setContentView (R. layout. main12); mImageView = (ImageView) findViewById (R. id. imageView); mButton = (Button) findViewById (R. id. button); mProgressBar = (ProgressBar) findViewById (R. id. progressBar); mButton. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {new myasynctask(.exe cute ("http://csdnimg.cn/www/images/csdnindex_logo.gif") ;}});} class MyAs YncTask extends AsyncTask <String, Integer, Bitmap >{@ Override protected Bitmap doInBackground (String... params) {publishProgress (0); // onProgressUpdate (Integer... progress) method HttpClient hc = new DefaultHttpClient (); publishProgress (30); HttpGet hg = new HttpGet (params [0]); final Bitmap bm; try {HttpResponse hr = hc.exe cute (hg); bm = BitmapFactory. decodeStream (hr. getEntity (). getContent ();} c Atch (Exception e) {return null;} publishProgress (100); return bm ;}@ Override protected void onProgressUpdate (Integer... values) {mProgressBar. setProgress (values [0]);} @ Override protected void onPostExecute (Bitmap result) {if (result! = Null) {Toast. makeText (AsyncTaskActivity. this, "image retrieved successfully", Toast. LENGTH_LONG ). show (); mImageView. setImageBitmap (result);} else {Toast. makeText (AsyncTaskActivity. this, "failed to get image", Toast. LENGTH_LONG ). show () ;}@ Override protected void onPreExecute () {mImageView. setImageBitmap (null); mProgressBar. setProgress (0); super. onPreExecute () ;}@ Override protected void onCancelled () {super. onCancelled (); mProgressBar. setProgress (0 );}}}

 

 

Related Article

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.