android 异步任务 AsyncTask

android 3,0之后就不允许在主线程进行网络操作,所以在开发中,在联网过程中必须使用异步线程,有俩种方式

1.AsyncTask

2.handler 

接下来使用AsyncTask的基本使用 示例:从网络下载图片,进度条更新下载进度。

package com.zx.progress;


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


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 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 String imageUrl="http://f.hiphotos.baidu.com/image/pic/item/a2cc7cd98d1001e93cbe5587ba0e7bec55e797b3.jpg";
private Button btn;
private ImageView iv;
private ProgressDialog dialog;//进度条
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog=new ProgressDialog(this);
dialog.setMessage("正在下载。。。");
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
btn=(Button) findViewById(R.id.button1);
iv=(ImageView) findViewById(R.id.imageView1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {


new MyTask().execute(imageUrl);
}
});
}


class MyTask extends AsyncTask{


@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.show();
}

//耗时任务在该方法中执行
@Override
protected Bitmap doInBackground(String... params) {

Bitmap bitmap=null;
HttpClient client=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(params[0]);
InputStream inputStream=null;
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
try {

 HttpResponse httpResponse=client.execute(httpGet);
 if(httpResponse.getStatusLine().getStatusCode()==200){ 
 
 inputStream=httpResponse.getEntity().getContent();
 long file_length=httpResponse.getEntity().getContentLength();//文件总长度
 int progress=0;
 int len=0;
 int value=0;
 byte[] data=new byte[1024];//每个读取1024个字节
 while((len=inputStream.read(data))!=-1){
 progress+=len;
 value=(int)(progress/(float)file_length*100);
 publishProgress(value);
 outputStream.write(data, 0, len);
 }
 byte[] result=outputStream.toByteArray();//转换为数组
 bitmap= BitmapFactory.decodeByteArray(result, 0, result.length);
 }
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{

}
return bitmap;
}

@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.setProgress(values[0]);//更新进度
}

@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
iv.setImageBitmap(result);
}

}


@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;
}


}

你可能感兴趣的:(android菜鸟,asynctask,异步)