您的位置:首页 > 其它

AsyncTask异步加载图片(显示进度条刻度)

2013-10-31 23:00 549 查看
MainActivity.java

package com.example.hasynctask;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
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 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 button;
private ImageView imageView;
private ProgressDialog dialog;
private final String PATH = "http://img1.bdstatic.com/img/image/9448718367adab44aed19135dceb11c8701a18bfbbf.jpg";	//图片地址
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);	//设置布局
dialog = new ProgressDialog(this);
dialog.setTitle("提示");
dialog.setMessage("正在下载图片。。。。。。");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);	//设置进度条为水平方向,默认为圆形
button = (Button) this.findViewById(R.id.button1);	//得到按钮组件
imageView = (ImageView) this.findViewById(R.id.imageView1);	//得到图像组件
//为按钮添加事件
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//创建任务线程并执行,传入地址参数
new MyTask().execute(PATH);
}
});
}
/*
* 创建异步任务类,执行异步下载图片.
* 第一个参数:接收的参数
* 第二个参数:进度值
* 第三个参数:返回的值
*/
class MyTask extends AsyncTask<String, Integer, byte[]>{
//最先执行的方法
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();	//设置UI主线程一直显示提示框
}
//后台执行的方法
@Override
protected byte[] doInBackground(String... params) {
byte[] result = null;
InputStream inputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();	//保存下载下来的输入流
HttpClient httpClient = new DefaultHttpClient();
try {
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse httpResponse = httpClient.execute(httpGet);
//result = EntityUtils.toByteArray(httpResponse.getEntity());	//把响应的实体转换成字节数组
long file_length = httpResponse.getEntity().getContentLength();//文件总长度
int total_length = 0;
byte[] data = new byte[1024];
int len = 0;
if(httpResponse.getStatusLine().getStatusCode()==200){
inputStream = httpResponse.getEntity().getContent();
while((len = inputStream.read(data))!=-1){
total_length += len;
publishProgress((int)((total_length/(float)file_length)*100));//更新进度
outputStream.write(data, 0, len);
}
}
result = outputStream.toByteArray();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
httpClient.getConnectionManager().shutdown();
}
return result;
}
//在doInBackground方法中通过调用publishProgress来间接调用这个方法
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}
//最后执行的方法,返回doInBackground结果
@Override
protected void onPostExecute(byte[] result) {
super.onPostExecute(result);
//从字节数组到图片的转换
Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
imageView.setImageBitmap(bitmap);
dialog.dismiss();
}

}

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

}


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=".MainActivity" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="107dp"
android:layout_marginTop="75dp"
/>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="73dp"
android:text="下载" />

</RelativeLayout>

运行结果



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: