Android AysncTask的使用

jopen 11年前發布 | 15K 次閱讀 Android Android開發 移動開發

  異步任務類讓你能夠在主線程中直接操作耗時的操作而不用重新開啟一個線程,在具體的開發中的時候UI線程是不會執行耗時的操作的,所以異步任務類是非常有用。

  要開發異步任務類,涉及到三個類型和4個方法。

   首先來看這三個類型,它們是三個泛型類:params,progress和result。

  官網對它的描述是:

The three types used by an asynchronous task are the following:

1.Params, the type of the parameters sent to the task upon execution.
2.Progress, the type of the progress units published during the background computation.
3.Result, the type of the result of the background computation.

  params表示通過execute()方法傳進來的參數的類型。

  progress表示progress的單位的類型。

  result表示在計算完成之后返回值的類型。


4個方法:onPreExecute()、doInBackground(String... params)、onProgressUpdate()、onPostExecute()四個方法。官網對于這四個方法的解釋為:

Android AysncTask的使用

下面實現一個打開網絡圖片的demo:

package com.app.main;

import org.apache.http.HttpEntity;
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 org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Main extends Activity {

    String url = "http://e.hiphotos.baidu.com/image/w%3D2048/sign=61711bd121a446237ecaa262ac1a730e/e850352ac65c10385f10af69b3119313b07e892a.jpg";
    ImageView imgView = null;
    Button btn = null;
    ProgressDialog dialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imgView = (ImageView) this.findViewById(R.id.imageview);
        btn = (Button) this.findViewById(R.id.btn);
        dialog = new ProgressDialog(this);
        dialog.setMessage("下載圖片中......");

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {

                new MyTask().execute(url);
            }

        });

    }

    class MyTask extends AsyncTask {

        @Override
        protected void onPreExecute() {

            super.onPreExecute();

            dialog.show();

        }

        @Override
        protected Bitmap doInBackground(String... params) {

            Bitmap bitmap = null;

            String url = params[0];

            HttpClient client = new DefaultHttpClient();

            HttpGet getMethod = new HttpGet(url);

            try {

                HttpResponse response = client.execute(getMethod);

                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();

                    byte[] data = EntityUtils.toByteArray(entity);

                    bitmap = BitmapFactory
                            .decodeByteArray(data, 0, data.length);

                }

            } catch (Exception e) {

            }

            return bitmap;
        }

        @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(Bitmap result) {

            super.onPostExecute(result);

            imgView.setImageBitmap(result);

            dialog.dismiss();
        }

    }

}

實現的效果如圖:

Android AysncTask的使用

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!