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=EntityUtils.toByteArray(httpEntity); //通过工厂类创建Bitmap对象 BitmapFactory.decodeByteArray(data, 0, data.length);*/ //获得输入流 in=httpResponse.getEntity().getContent(); //获得文件的总长度 long file_length=httpResponse.getEntity().getContentLength(); //计算总长度 int total_len=0; int len=0; byte[] buffer=new byte[1024]; try{ while((len=in.read(buffer))!=-1) { total_len+=len; <span style="color:#ff0000;">//刻度计算公式</span> int value=(int)(total_len/((float)file_length)*100); <span style="color:#ff6666;">//发布进度条的刻度</span> publishProgress(value); //写入输出流 out.write(buffer, 0, len); } //内存输出流转换成字节数组 bitmap=BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.toByteArray().length); }catch(Exception e) { }finally{ if(in!=null) { in.close(); } } } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); image.setImageBitmap(result); dialog.dismiss(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); dialog.setProgress(values[0]); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }其中
publishProgress(value);是可以发送几个对象给
onProgressUpdate()方法的。
原文地址:http://blog.csdn.net/u014600432/article/details/41280777