1.在主线程开启子线程下载数据。
2.下载完毕后,向主线程发送消息。
3.在主线程的handler中处理消息。
4.加上连接网络的权限。
package com.example.hellodemo2;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView imageview;
Bitmap bm;
private final Handler handler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
imageview.setImageBitmap(bm);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview = (ImageView) findViewById(R.id.imageView1);
// 开启子线程连接网络
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
long startTime = System.currentTimeMillis();
String urlstr = "http://www.molyapp.com/theme/images/start.png";
URL url;
try {
url = new URL(urlstr);
URLConnection con = url.openConnection();
HttpURLConnection imageConnection = (HttpURLConnection) con;
// 获取输入流
InputStream inputStream = imageConnection.getInputStream();
// 获取图片的长度
long length = imageConnection.getContentLength();
bm = BitmapFactory.decodeStream(inputStream);
// 获取输出流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int sum = 0;
int read = 0;
int bytecount = (int) Math.min(buffer.length, length - sum);
while ((read = inputStream.read(buffer, 0, bytecount)) != -1) {
// 刚开始每次读获取buffer的长度。最后读取剩下的。
byteArrayOutputStream.write(buffer, 0, read);
sum += read;
}
Log.v("haha", sum + "");
System.out.println("readBytes=" + sum);
long fetchImageTime = System.currentTimeMillis()
- startTime;
handler.sendEmptyMessage(0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}