2010-05-25 55 views

回答

6

我强烈建议使用AsyncTask来代替。我最初使用URL.openStream,但它有issues

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你应该只需要关闭最外面的流,但是it appears to be more complicated。但是,如果我们无法关闭BufferedInputStream,我将首先关闭最内层的流,以确保它关闭。

我们在最后关闭,以便异常不会阻止它们被关闭。如果一个异常阻止了它们的初始化,我们将考虑这些流的可能性为null。如果我们在关闭期间出现异常,我们只需登录并忽略它。即使这可能无法正常工作,如果发生运行时错误。

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

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

3

你做了很多方法,但我能想到的simplist方法是这样的:

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。

+0

我其实忘了在我原来的代码中关闭我的流。尽管如此,你真的应该关闭你的流 – Casebash 2010-05-26 00:54:03