android 获取网络图片

来源:互联网 发布:阿里云企业邮箱ip地址 编辑:程序博客网 时间:2024/04/30 01:19

public Bitmap getBitmap( String url ){  //图片URL
URL imageUrl = null ;
Bitmap bitmap = null ;
try {
imageUrl = new URL(url) ;
}catch (MalformedURLException e){
e.printStackTrace();
}
try{
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setDoInput(true); 
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
}catch (IOException e){
e.printStackTrace();
}
return bitmap ;
}

在程序中直接引用函数getBitmap会导致运行时错误。使用代码如下。
Bitmap image ;

Handler myHandler =new Handler(){
public void handleMessage(Message msg)
{
switch(msg.what){
case 1:
//图片已获取,执行
相应操作
}
}
};


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

new Thread(new Runnable(){
public void run()
{
image = getBitmap("http://t.douban.com/spic/s1747553.jpg");
Message msg=new Message();
msg.what=1;
MainActivity.this.myHandler.sendMessage(msg);
}
}).start();

}