Android asynchronous tasks -- AsyncTask (with Download Image Demo using AsyncTas

  We often need to handle synchronization programming tasks and the asynchronous task, there is a character in the Android, is the UI thread is not thread safe. The so-called UI is not thread safe is our main thread (the first thread start) is not online process operation outside of the main thread resources. Because the main thread of resources are not synchronized. It is generally said that the thread synchronization.

  When we do the Android application process, need to download for example in a sub thread performs some time-consuming operation,, etc. In this case we generally use Handler and thread based processing, sub thread is responsible for processing time operation, then notify the Handler UI update. The combination of Handler and Zi Xiancheng processing for control precision is high or the task time-consuming or repeated situation. In addition to the use of a combination of Handler and thread, Android also provides another choice for us, it is today to say AsyncTask.

  AsyncTask is using Handler and thread model, only Google gave it a good package. Below we have a look how to use AsyncTask.

 (PS: The new QQ group, who are interested can join together: Android group: 322599434)

1,The definition of android.os.AsyncTask

public abstract class AsyncTask<Params, Progress, Result> 

These parameters are generic definition, so we can be our own data types defined as parameters, and if not relevant to the needs of transmission, can be passed to the Void.

2,The AsyncTask interface

//Implementation of the asynchronous task, start asynchronous tasks needed to perform this interface

public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); }

//In the execute () is executed immediately after the call, can do some task initialization

protected void onPreExecute() { }

//In the onPreExecute () after the execution execution, the execution of some time-consuming operation, this method will receive input parameters and return results. 

//In the implementation process can call publishProgress () to update the schedule information

protected abstract Result doInBackground(Params... params);

//In the call to publishProgress (Progress... Values), callback this method, is used to update the schedule information

protected void onProgressUpdate(Progress... values)



//DoInBackground is executed, this method is used to update the callback, the interface information

protected void onPostExecute(Result result) { }

  Here are some important interface and method of AsyncTask, we can see that most are empty and there is a virtual function method. We inherit the AsyncTask, all need to override the methods above, we can perform the appropriate operation.

3,The AsyncTask example

The following is a use AsyncTask to download the pictures the examples I prepared, this example function is to use the AsyncTask to download a picture.

    private class DownLoad extends AsyncTask<String, Integer, String> 
        //The onPreExecute method in execute () after the implementation of
        protected void onPreExecute() 
            Log.i(TAG, "onPreExecute() enter");  
            mShowLogTextView.setText("onPreExecute. . . begin downLoad");  
        //Inside the doInBackground method perform background tasks, cannot update UI inside, otherwise there is abnormal. 
        protected String doInBackground(String... params) 
            Log.i(TAG, "doInBackground(String... params) enter");  
            URL imageUrl=null;
                imageUrl=new URL(params[0]);
            catch (MalformedURLException e) 
                Log.e(TAG, e.getMessage());
                //Use HttpURLConnection to open the connection
                HttpURLConnection urlConn=(HttpURLConnection)imageUrl.openConnection();
                //The obtained data into InputStream
                InputStream is=urlConn.getInputStream();
                //Convert InputStream to Bitmap
                //Cannot update UI here, otherwise there is abnormal******
            }catch(IOException e)
            return "ok";
        //The onProgressUpdate method is used to update the progress information  
        protected void onProgressUpdate(Integer... progresses) 
            Log.i(TAG, "onProgressUpdate(Integer... progresses) enter");  
            mShowLogTextView.setText("onProgressUpdate Downloading...");  
        //OnPostExecute for doInBackground is executed, the update of the interface UI. 
        //Result doInBackground returns a result
        protected void onPostExecute(String result) 
            Log.i(TAG, "onPostExecute(Result result) called");  
            mShowLogTextView.setText("Down load finish result="+result);  
        //The onCancelled method is used to cancel the Task execution, update UI
        protected void onCancelled() 
            Log.i(TAG, "onCancelled() called");  

  It is inherited from the AsyncTask class, override the inside correlation method and so on, it can be seen from the above AsyncTask's main task is to doInBackground implementation. Then onPostExecute last updated results. Method for AsyncTask execution is very simple, as long as the call execute and pass the relevant parameters.

public void onClick(View v)
    if (v==mPlayMusicButton)
        //To download the address mythou

  Here the incoming parameters are as doInBackground method, here into the picture of URL, then perform a download operation. Here to talk about AsyncTask use need to pay attention to things.

 Below is the example implementation effect:

AsyncTask Demo: click here to download the code 

Edited by mythou

The original Bowen, reprint please indicate the source  

Posted by Gabriel at November 18, 2013 - 3:52 AM