我们在布局界面中添加一个ImageView
接着
我们编写一个getPicture()方法用来返回一个Bitmap对象,用来获取网络图片:
public Bitmap getPicture(String path){
Bitmap bm=null;
try{
URL url=new URL(path);
URLConnection connection=url.openConnection();
connection.connect();
InputStream inputStream=connection.getInputStream();
bm= BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
接着
然后我们在oncreate方法中添加一个新线程:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
imageView= (ImageView) findViewById(R.id.imageView);
new Thread(new Runnable() {
@Override
public void run() {
final Bitmap bitmap=getPicture("http://h.hiphotos.baidu.com/news/q%3D100/sign=be8e90f30cfa513d57aa68de0d6d554c/c75c10385343fbf29d10a30cb47eca8065388fe4.jpg");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
imageView.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
}).start();
}