您的位置:首页 > 理论基础 > 计算机网络

AsyncTask与HttpURLConnection下载网络图片

2016-08-18 20:25 399 查看


使用AsyncTask可以更加方便的在子线程中对UI进行操作。

AsyncTask是个抽象类,使用它必须要创建一个子类去继承它。他有三个泛型的参数,

<?xml version="1.0" encoding="utf-8"?>
<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="yifang.zhsong.ansyctaskdemo.MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download"
android:id="@+id/bt_download"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="43dp" />

<ImageView
android:layout_width="500dp"
android:layout_height="500dp"
android:id="@+id/iv_picture" />
</RelativeLayout>


MainActivity部分的代码

package yifang.zhsong.ansyctaskdemo;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

private Button button;
private ImageView image;

private ProgressDialog dia;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.bt_download);
image = (ImageView) findViewById(R.id.iv_picture);
//定义进度条
dia = new ProgressDialog(this);
dia.setTitle("提示信息");
dia.setMessage("下载中,请稍后");
dia.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//设置点击进度条外部,不响应;
dia.setCancelable(false);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new MyTask().execute();
}
});
}

//Sting 表示传入的值, Integer  代表进度 ,  Bitmap 代表返回的值
public class MyTask extends AsyncTask<String, Integer, Bitmap> {

//任务执行之前的准备工作。
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dia.show();
}

//主要完成耗时操作
@Override
protected Bitmap doInBackground(String... arg0) {
// TODO Auto-generated method stub
HttpURLConnection connection = null;

Bitmap bitmap = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream inputStream = null;
try {
URL url = new URL("http://imglf0.nosdn.127.net/img/akF3Q3JLbzVNWExja3g3d1B5a0NRcW50OUFtNTBoNTRaYkRjdEo2WlBDeGRTRkNGUUVraGxnPT0.jpg?imageView&thumbnail=500x0&quality=96&stripmeta=0&type=jpg");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
inputStream = connection.getInputStream();

//先获得文件的总长度,
int fileLength = connection.getContentLength();
int len = 0;
byte[] data = new byte[1024];
int total_length = 0;
int value = 0;
while ((len = inputStream.read(data)) != -1) {
total_length += len;
value = ((total_length / fileLength) * 100);
//调用update函数,更新进度
publishProgress(value);
outputStream.write(data, 0, len);
Thread.sleep(500);
}
byte[] result = outputStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
inputStream.close();
outputStream.close();
connection.disconnect();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
outputStream.close();
connection.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return bitmap;
}

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

//主要完成耗时操作
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
dia.dismiss();
image.setImageBitmap(result);
}
}

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