Android AysncTask的使用
jopen
11年前
异步任务类让你能够在主线程中直接操作耗时的操作而不用重新开启一个线程,在具体的开发中的时候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()四个方法。官网对于这四个方法的解释为:
下面实现一个打开网络图片的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(); } } }
实现的效果如图: