Android图片获取

Nor*_*sUp 3 android

从android程序中的url获取图像的最简单方法是什么?

Cas*_*ash 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");
   }
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,关闭流/连接和异常处理是困难的.根据Sun文档,您只需要关闭最外层的流,但它看起来更复杂.但是,我正在关闭最内层的流,以确保它关闭,如果我们不能关闭BufferedInputStream.

我们最终关闭,以便异常不会阻止它们被关闭.null如果异常阻止它们被初始化,我们会考虑流的可能性.如果我们在关闭期间有异常,我们只需记录并忽略它.如果发生运行时错误,即使这可能也无法正常工作.

您可以AsyncTask按如下方式使用该类.在中开始动画onPreExecute.更新进度onProgressUpdate.onPostExecute应该处理实际的图像.使用onCancel允许用户取消操作.启动它AsyncTask.execute.

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