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();
}