现在的位置: 首页 > 综合 > 正文

android异步任务1

2017年11月18日 ⁄ 综合 ⁄ 共 4562字 ⁄ 字号 评论关闭

android异步任务主要用来执行一些耗时操作,比如联网,访问数据库等。由于他有两个方法运行在UI线程,可以不用向多线程那样发消息就能方便的实现更新UI。个人比较喜欢用异步任务来完成有需要更新UI的耗时操作。

public class MainActivity extends Activity {

 

private Button btn;

private ImageView image;

private String imagePath="http://t10.baidu.com/it/u=1814818569,2539010546&fm=59";

private ProgressDialog progressDialog;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

btn=(Button)findViewById(R.id.button1);

image=(ImageView)findViewById(R.id.imageView1);

progressDialog=new ProgressDialog(this);

progressDialog.setTitle("提示信息");

progressDialog.setMessage("正在下载,请稍等......");

btn.setOnClickListener(new OnClickListener(){

 

@Override

public void onClick(View arg0) {

//执行异步任务的操作

new  MyAsyncTask().execute(imagePath);

}

});

}

/**

 * 使用异步任务的规则:

 * 第一,定义一个AsyncTask的子类第一个参数是表示要执行的任务,通常是访问网络的路径。

 * 第二个参数通常是表示进度的刻度。第三个参数表示任务执行的返回结果

 * @author YangQuanqing yqq

 *

 */

private class MyAsyncTask extends AsyncTask<String,Void,Bitmap>{

 

//任务执行之前的操作

@Override

protected void onPreExecute() {

progressDialog.show();

super.onPreExecute();

}

//主要完成耗时操作

@Override

protected Bitmap doInBackground(String...params) {

Bitmap bitmap=null;

//通过一个网络连接类来获取网络资源

HttpClient httpClient=new DefaultHttpClient();

//可变参数,只有一个,采用GET请求方式

HttpGet httpGet=new HttpGet(params[0]);

try {

//获得通过GET方式获得的响应

HttpResponse httpResponse=httpClient.execute(httpGet);

//判断请求响应是否成功

if(httpResponse.getStatusLine().getStatusCode()==200)

{

//取出响应实体

HttpEntity httpEntity=httpResponse.getEntity();

//把响应实体转换成字节数组

byte[]data= EntityUtils.toByteArray(httpEntity);

//InputStream in=httpEntity.getContent();

//byte[]data=in.toString().getBytes();

//用位图工厂类编码字节数组获得请的到的位图

bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);

}

catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return bitmap;

}

//主要更新UI的操作

@Override

protected void onPostExecute(Bitmap result) {

//更新图片

image.setImageBitmap(result);

progressDialog.dismiss();

super.onPostExecute(result);

}

}

}

 

 

异步任务2刻度条

 

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;

//刻度计算公式

int value=(int)(total_len/((float)file_length)*100);

//发布进度条的刻度

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]);

}

}}}

【上篇】
【下篇】

抱歉!评论已关闭.