什么是在Android程序中从URL获取图像的最简单方法?
我强烈建议使用AsyncTask。我最初使用了URL.openStream, 但它存在问题。
class DownloadThread extends AsyncTask<URL,Integer,List<Bitmap>>{
protected List<Bitmap> doInBackground(URL... urls){
InputStream rawIn=null;
BufferedInputStream bufIn=null;
HttpURLConnection conn=null;
try{
List<Bitmap> out=new ArrayList<Bitmap>();
for(int i=0;i<urls.length;i++){
URL url=urls[i];
url = new URL("http://mysite/myimage.png");
conn=(HttpURLConnection) url.openConnection()
if(!String.valueOf(conn.getResponseCode()).startsWith('2'))
throw new IOException("Incorrect response code "+conn.getResponseCode()+" Message: " +getResponseMessage());
rawIn=conn.getInputStream();
bufIn=new BufferedInputStream();
Bitmap b=BitmapFactory.decodeStream(in);
out.add(b);
publishProgress(i);//Remove this line if you don't want to use AsyncTask
}
return out;
}catch(IOException e){
Log.w("networking","Downloading image failed");//Log is an Android specific class
return null;
}
finally{
try {
if(rawIn!=null)rawIn.close();
if(bufIn!=null)bufIn.close();
if(conn!=null)conn.disconnect();
}catch (IOException e) {
Log.w("networking","Closing stream failed");
}
}
}
}
在这种情况下,关闭流/连接和异常处理很困难。根据Sun Documentation,您只需要关闭最外层的流,但是看起来更加复杂。然而,我首先关闭最内层的流,以确保在无法关闭BufferedInputStream
时它已经被关闭。
我们在finally中关闭,以防止异常阻止它们被关闭。如果异常导致流未初始化,则考虑流可能为null
的情况。如果在关闭过程中出现异常,我们只需记录并忽略此异常。即使如此,如果发生运行时错误,这也可能无法正常工作。
您可以按以下方式使用AsyncTask
类。在onPreExecute
中启动动画。在onProgressUpdate
中更新进度。 onPostExecute
应处理实际图像。使用onCancel
允许用户取消操作。使用AsyncTask.execute
启动它。
有很多种方法可以做到这一点,但我能想到的最简单的方法是这样的:
Bitmap IMG;
Thread t = new Thread(){
public void run(){
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL("YOUR URL");
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
IMG = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
// ...send message to handler to populate view.
mHandler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e(DEB, "Remtoe Image Exception", e);
mHandler.sendEmptyMessage(1);
} finally {
}
}
};
t.start();
。
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
switch(msg.what){
case 0:
(YOUR IMAGE VIEW).setImageBitmap(IMG);
break;
case 1:
onFail();
break;
}
}
};