首页 > 代码库 > android异步任务学习笔记

android异步任务学习笔记

android异步任务可以很方便的完成耗时操作并更新UI,不像多线程还要利用消息队列,子线程发消息给主线程,主线程才能更新UI。总之,android异步任务把多线程的交互进行进一步的封装,用起来跟方便。

如下是异步任务demo代码:

完成异步下载图片,更新界面。

package com.example.android_async_task2;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {
private Button btn=null;
private ImageView image=null;
private String image_path="http://f2.sjbly.cn/m13/0729/1459/6947edn_690x459_b.jpg";
private ProgressDialog dialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn=(Button)this.findViewById(R.id.button1);
		dialog=new ProgressDialog(this);
		dialog.setTitle("提示信息");
		dialog.setMessage("下载中,请稍等......");
		//设置进度条的样式
		dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		//屏幕不失去焦点
		dialog.setCancelable(false);
		image=(ImageView)this.findViewById(R.id.imageView1);
		btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				new MyTask().execute(image_path);
				
			}
			
			
		});
	}

	public class MyTask extends AsyncTask<String,Integer,Bitmap>
	{
		@Override
		protected void onPreExecute() {
			dialog.show();
			super.onPreExecute();
		}
		
		@Override
		protected Bitmap doInBackground(String... params) {
			//定义一个内存流,不需要关闭
			ByteArrayOutputStream out= new ByteArrayOutputStream();
			//定义一个输入流
			InputStream in=null;
			Bitmap bitmap=null;
			//通过HttpClient类获取网络资源
			HttpClient httpClient=new DefaultHttpClient();
			//设置请求方式(注意请求地址URL要写入!!!)
			HttpGet httpGet=new HttpGet(params[0]);
			
			try {
				//获得请求状态
				HttpResponse httpResponse=httpClient.execute(httpGet);
				//判断请求状态结果码
				if(httpResponse.getStatusLine().getStatusCode()==200)
				{
					/*//通过一个实体类获得响应的实体
					HttpEntity httpEntity=httpResponse.getEntity();
					//通过一个实体工具类获得实体的字节数组
					byte[]data=http://www.mamicode.com/EntityUtils.toByteArray(httpEntity);>其中
publishProgress(value);
是可以发送几个对象给
onProgressUpdate()方法的。

DEMO下载:http://download.csdn.net/detail/u014600432/8175337

android异步任务学习笔记