1. 程式人生 > >Android非同步處理二:AsynTask介紹和使用AsyncTask非同步更新UI介面

Android非同步處理二:AsynTask介紹和使用AsyncTask非同步更新UI介面

(1)AsyncTask的介紹

這裡寫圖片描述

通過上圖中的AsyncTask的原始碼結構圖可以看到,主要用於過載的方法是doInBackground(),onPreExecute()、onPostExecute()、onProgressUpdate()、onCancelled()、publishProgress()等前邊是”黃色的菱形“圖示的,下邊詳細介紹這些方法的功能:

AsyncTask的建構函式有三個模板引數:

1.Params,傳遞給後臺任務的引數型別。
2.Progress,後臺計算執行過程中,進步單位(progress units)的型別。(就是後臺程式已經執行了百分之幾了。)
3.Result,

後臺執行返回的結果的型別。
AsyncTask並不總是需要使用上面的全部3種類型。標識不使用的型別很簡單,只需要使用Void型別即可。

doInBackground(Params…)

原始碼註釋:

 /**
     * 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);

正在後臺執行:doInBackground(Params…),該回調函式由後臺執行緒在onPreExecute()方法執行結束後立即呼叫。通常在這裡執行耗時的後臺計算。計算的結果必須由該函式返回,並被傳遞到onPostExecute()中。在該函式內也可以使用publishProgress(Progress…)來發佈一個或多個進度單位(unitsof progress)。這些值將會在onProgressUpdate(Progress…)中被髮布到UI執行緒。

onPreExecute()

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

準備執行:onPreExecute(),該回調函式在任務被執行之後立即由UI執行緒呼叫。這個步驟通常用來建立任務,在使用者介面(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) {
    }

完成後臺任務:onPostExecute(Result),當後臺計算結束後呼叫。後臺計算的結果會被作為引數傳遞給這一函式。

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) {
    }

完成後臺任務:onPostExecute(Result),當後臺計算結束後呼叫。後臺計算的結果會被作為引數傳遞給這一函式。

onCancelled()

取消任務:onCancelled (),在呼叫AsyncTask的cancel()方法時呼叫

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();
        }
    }

主要用於顯示進度。

(2)使用AsyncTask非同步更新UI介面

AsyncTaskActivity .java作為啟動頁面的檔案

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.execute("http://g.hiphotos.baidu.com/image/pic/item/b3119313b07eca80d340a3e0932397dda1448374.jpg");
            }
        });
    }

    class GetImageTask extends AsyncTask<String,Integer,Bitmap> {//繼承AsyncTask

        @Override
        protected Bitmap doInBackground(String... params) {//處理後臺執行的任務,在後臺執行緒執行
            publishProgress(0);//將會呼叫onProgressUpdate(Integer... progress)方法
            HttpClient httpClient = new DefaultHttpClient();
            publishProgress(30);
            HttpGet httpGet = new HttpGet(params[0]);//獲取csdn的logo
            final Bitmap bitmap;
            try {
                HttpResponse httpResponse = httpClient.execute(httpGet);
                bitmap = BitmapFactory.decodeStream(httpResponse.getEntity().getContent());
            } catch (Exception e) {

                return null;
            }
            publishProgress(100);
            //mImageView.setImageBitmap(result); 不能在後臺執行緒操作ui
            return bitmap;
        }

        protected void onProgressUpdate(Integer... progress) {//在呼叫publishProgress之後被呼叫,在ui執行緒執行
            mProgressBar.setProgress(progress[0]);//更新進度條的進度
         }

         protected void onPostExecute(Bitmap result) {//後臺任務執行完之後被呼叫,在ui執行緒執行
             if(result != null) {
                 Toast.makeText(AsyncTaskActivity.this, "成功獲取圖片", Toast.LENGTH_LONG).show();
                 mImageView.setImageBitmap(result);
             }else {
                 Toast.makeText(AsyncTaskActivity.this, "獲取圖片失敗", Toast.LENGTH_LONG).show();
             }
         }

         protected void onPreExecute () {//在 doInBackground(Params...)之前被呼叫,在ui執行緒執行
             mImageView.setImageBitmap(null);
             mProgressBar.setProgress(0);//進度條復位
         }

         protected void onCancelled () {//在ui執行緒執行
             mProgressBar.setProgress(0);//進度條復位
         }  
    }
}

佈局檔案:

<?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="下載圖片" >
    </Button>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

同樣需要開啟訪問網路的許可權和設定啟動介面

另外我們使用AsynTask的時候,需要注意的是
這裡寫圖片描述