package com.example.ofu.httphemo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity{
private ImageView img=null;
Handler handler =new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
//在这里取得从子线程发送来的msg
//取出bitmap对象,给img
Bitmap bitmap=(Bitmap)msg.obj;
if(bitmap!=null){
img.setImageBitmap(bitmap);
}
return false;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img=(ImageView)findViewById(R.id.imageView);
MyThread myThread=new MyThread();
myThread.start();
}
//在安卓中,不允许在子线程直接操作UI线程里面的控件,要通过Handler
//进行线程之间的沟通。
//定义一个子线程内部类继承自Thread进行耗时操作
public class MyThread extends Thread{
public void run(){
HttpURLConnection conn=null;
try {
//定义图片地址
URL url=new URL("http://pic.nipic.com/2007-11-09/200711912453162_2.jpg");
//打开网络连接
conn=(HttpURLConnection)url.openConnection();
//设置网络超时
conn.setConnectTimeout(5000);
//获取网络请求之后的响应码
// 200 为请求成功 if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
//获取输入流
InputStream inputStream=conn.getInputStream();
//若输入流不为空,则装换为BitMap对象
//通过handler发送至主线程。
if(inputStream!=null){
Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
Message msg=new Message();
msg.obj=bitmap;
handler.sendMessage(msg);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (conn != null) conn.disconnect();
}
}
}
}
Android 下载网络图片
最新推荐文章于 2021-04-22 18:42:33 发布