Android 图片获取

3
什么是在Android程序中从URL获取图像的最简单方法?
2个回答

6

我强烈建议使用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启动它。

值得注意的是,源代码和许可证允许我们在非Android项目中使用该类。

3

有很多种方法可以做到这一点,但我能想到的最简单的方法是这样的:

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

通过启动一个线程并添加处理程序,您可以在下载期间加载图像而不会锁定UI。

我在原始代码中实际上忘记关闭我的流了。不过你真的应该在finally块中关闭你的流。 - Casebash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接