Handler、子线程下载图片-笔记

package com.example.android20_handlertomain;


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


import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;


public class MainActivity extends Activity {
private ImageView imageView;
private ProgressDialog progressDialog;
Handler handler = new Handler() {


@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 411) {
progressDialog.setProgress(msg.arg1);
} else if (msg.what == 412) {
byte[] data = (byte[]) msg.obj;
Bitmap mitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
imageView.setImageBitmap(mitmap);
}
}
};


private String urlString = "http://a.hiphotos.baidu.com/image/pic/item/8b13632762d0f703395323c10afa513d2797c5ce.jpg";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView1);


{
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("提示");
progressDialog.setIcon(R.drawable.ic_launcher);
progressDialog
.setSecondaryProgress(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("下载中...");
progressDialog.show();
}


new Thread(new MyThread()).start();
}


public class MyThread implements Runnable {


@Override
public void run() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = null;
try {
HttpURLConnection conn = (HttpURLConnection) (new URL(urlString))
.openConnection();
conn.setReadTimeout(3000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
int maxSize = conn.getContentLength();
int size = 0;
byte[] buffer = new byte[1024];
int len = -1;
is = conn.getInputStream();
while ((len = is.read(buffer)) != -1) {
size += len;
bos.write(buffer, 0, len);
bos.flush();
Message message = Message.obtain(handler, 411,
(int) (size / (float) maxSize * 100), 0);
message.sendToTarget();
}
Message message = Message.obtain(handler, 412,
bos.toByteArray());
message.sendToTarget();
progressDialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值