Android asynchronous processing 2: AsynTask introduction and use AsyncTask to asynchronously update the UI interface, asyntaskasynctask

Source: Internet
Author: User

Android asynchronous processing 2: AsynTask introduction and use AsyncTask to asynchronously update the UI interface, asyntaskasynctask

In the previous article (http://blog.csdn.net/xlgen157387/article/details/45269389) introduced the use of Thread + Handler to implement non-UI Thread UI update method steps, below do how homogeneous AsyncTask asynchronous tasks to update the UI interface.

(1) Introduction to AsyncTask

The source code structure of AsyncTask shows that the methods used for reload are doInBackground (), onPreExecute (), onPostExecute (), onProgressUpdate (), onCancelled (), and publishProgress () when the front side is a "yellow diamond" icon, the functions of these methods are described below:

The AsyncTask constructor has three template parameters:

1. Params,Parameter type passed to the background task.
2. Progress,The type of progress unit during background computing execution. (That is, the background program has executed a few percent .)
3. Result,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.

DoInBackground (Params ...)

Source code comment:

 /**     * Override this method to perform a computation on a background thread. The     * specified parameters are the parameters passed to {@link #execute}     * by the caller of this task.     *     * This method can call {@link #publishProgress} to publish updates     * on the UI thread.     *     * @param params The parameters of the task.     *     * @return A result, defined by the subclass of this task.     *     * @see #onPreExecute()     * @see #onPostExecute     * @see #publishProgress     */    protected abstract Result doInBackground(Params... params);

Running in the background: doInBackground (Params ...), This 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 in onProgressUpdate (Progress ...) Is released to the UI thread.

OnPreExecute ()
  /**     * Runs on the UI thread before {@link #doInBackground}.     *     * @see #onPostExecute     * @see #doInBackground     */    protected void onPreExecute() {    }

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.

OnPostExecute ()
/**     * <p>Runs on the UI thread after {@link #doInBackground}. The     * specified result is the value returned by {@link #doInBackground}.</p>     *      * <p>This method won't be invoked if the task was cancelled.</p>     *     * @param result The result of the operation computed by {@link #doInBackground}.     *     * @see #onPreExecute     * @see #doInBackground     * @see #onCancelled(Object)      */    @SuppressWarnings({"UnusedDeclaration"})    protected void onPostExecute(Result result) {    }

Background task completed: onPostExecute (Result), called after the background computing is complete. The result of background computing is passed as a parameter to this function.

OnProgressUpdate ()
 /**     * Runs on the UI thread after {@link #publishProgress} is invoked.     * The specified values are the values passed to {@link #publishProgress}.     *     * @param values The values indicating progress.     *     * @see #publishProgress     * @see #doInBackground     */    @SuppressWarnings({"UnusedDeclaration"})    protected void onProgressUpdate(Progress... values) {    }

Background task completed: onPostExecute (Result), called after the background computing is complete. The result of background computing is passed as a parameter to this function.

OnCancelled ()

Cancel task: onCancelled (), called when the cancel () method of AsyncTask is called

PublishProgress ()
/**     * This method can be invoked from {@link #doInBackground} to     * publish updates on the UI thread while the background computation is     * still running. Each call to this method will trigger the execution of     * {@link #onProgressUpdate} on the UI thread.     *     * {@link #onProgressUpdate} will note be called if the task has been     * canceled.     *     * @param values The progress values to update the UI with.     *     * @see #onProgressUpdate     * @see #doInBackground     */    protected final void publishProgress(Progress... values) {        if (!isCancelled()) {            sHandler.obtainMessage(MESSAGE_POST_PROGRESS,                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();        }    }

It is mainly used to display the progress.

(2) Use AsyncTask to asynchronously update the UI

AsyncTaskActivity. java is the file used to start the page.

Public class AsyncTaskActivity extends Activity {private ImageView mImageView; private Button mButton; private ProgressBar mProgressBar; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. asyntask_main); mImageView = (ImageView) findViewById (R. id. imageView); mButton = (Button) findViewById (R. id. button); mProgressBar = (ProgressBar) FindViewById (R. id. progressBar); mButton. setOnClickListener (new OnClickListener () {public void onClick (View v) {GetImageTask task = new GetImageTask (); task.exe cute ("http://g.hiphotos.baidu.com/image/pic/item/b3119313b07eca80d340a3e0932397dda1448374.jpg ");}});} class GetImageTask extends AsyncTask <String, Integer, Bitmap> {// inherit AsyncTask @ Override protected Bitmap doInBackground (String... param S) {// process the tasks executed in the background, and execute publishProgress (0) in the background thread; // onProgressUpdate (Integer... progress) method HttpClient httpClient = new DefaultHttpClient (); publishProgress (30); HttpGet httpGet = new HttpGet (params [0]); // obtain the csdn logo final Bitmap bitmap; try {HttpResponse httpResponse = httpClient.exe cute (httpGet); bitmap = BitmapFactory. decodeStream (httpResponse. getEntity (). getContent ();} catch (Exception e) {re Turn null;} publishProgress (100); // mImageView. setImageBitmap (result); ui return bitmap cannot be operated in the background thread;} protected void onProgressUpdate (Integer... progress) {// called after publishProgress is called, and mProgressBar is executed in the ui thread. setProgress (progress [0]); // update progress bar} protected void onPostExecute (Bitmap result) {// called after the background task is executed, execute 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 () ;}} protected void onPreExecute () {// In doInBackground (Params ...) previously called and mImageView is executed in the ui thread. setImageBitmap (null); mProgressBar. setProgress (0); // progress bar reset} protected void onCancelled () {// execute mProgressBar In the ui thread. setProgress (0); // progress bar reset }}}

Layout 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"> <ProgressBar android: id = "@ + id/progressBar" style = "? Android: attr/progressBarStyleHorizontal "android: layout_width =" fill_parent "android: layout_height =" wrap_content "> </ProgressBar> <Button android: id =" @ + id/button "android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Download image"> </Button> <ImageView android: id = "@ + id/imageView" android: layout_width = "wrap_content" android: layout_height = "wrap_content"/> </LinearLayout>

You also need to enable the network access permission and set the startup interface.

When using AsynTask, note that

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.