最近在总结Handler,所以引申了一下,这几天把老罗的有关异步的视频看了一遍,觉得介绍的挺好的,虽然还不是很清楚,但是先把自己能写的都先放上来。
首先,什么是异步,比如我们在进行网络操作的时候,Android是不允许我们在主线程中直接进行的,需要我们去开辟一个子线程进行一个耗时任务,而这个子线程对于主线程来说就是异步的,最后再将子线程上的操作更新到主线程上。
AsyncTask类中,主要用到的回调函数是:doInBackground(),onPreExecute(),onPostExecute()。在这个类中,三个参数的意义通常是:1.访问网络的路径,2.进度的刻度,3.任务执行的返回结果。而onPreExecute()是指在任务执行之前的操作;doInBackground()表示的是耗时的任务;onPostExecute()主要是更新UI操作。另外,在doInBackground()方法异步处理的时候,如果希望通知主线程一些数据(如:处理进度)。这时,可以调用publishProgress()方法。这时,主线程会调用AsynTask子类的onProgressUpdate()方法进行处理。
MainActivity.java
package com.whisker.asynctask_demo;
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.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 MainActivity extends Activity {
private String path = "http://pic.nipic.com/2007-11-09/2007119122519868_2.jpg";
private Button button;
private ImageView imageView;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
imageView = (ImageView) findViewById(R.id.imageView1);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Tips");
progressDialog.setMessage("Downloading..");
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
new MyTask().execute(path);
}
});
}
public class MyTask extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
Bitmap bitmap = null;
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200){
HttpEntity httpEntity = httpResponse.getEntity();
byte[] data = EntityUtils.toByteArray(httpEntity);
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
imageView.setImageBitmap(result);
progressDialog.dismiss();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.whisker.asynctask_demo.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="下载图片" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="120dp"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
效果图: