1

有人可以帮我看看这个图片下载代码吗?我希望它在后台运行,但根据 Android文档,似乎 new Thread(new Runnable()) 绝对不是要走的路,而且我不知道还有什么方法可以解决这个问题:

// caller
while( exhibitorCursor.moveToNext() )
{
  new Thread(new Runnable()
  {
    public void run()
    {
      downloadImage(exhibitorId, exhibitorString, DOWNLOAD_EXHIBITOR);
    }
  }).start();
}

// first function
public void downloadImage(long id, String externalImageUrl, int type)
{
  // logic junk here

  if( !(new File(localImageName).exists()) )
  {
    DownloadFromUrl(externalImageUrl, localImageName);
  }
}

// second function
public void DownloadFromUrl(String fileUrl, String fileName)
{
  // this is the downloader method
  try
  {
    URL url = new URL(fileUrl);

    File file = new File(fileName);

    URLConnection ucon = url.openConnection();

    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is, 8192);

    ByteArrayBuffer baf = new ByteArrayBuffer(50);
    int current = 0;
    while( (current = bis.read()) != -1 )
    {
      baf.append((byte)current);
    }

    /* Convert the Bytes read to a String. */
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(baf.toByteArray());
    fos.close();
  }
  catch( IOException e )
  {
    Log.d("ImageManager", "Error: " + e);
  }

}

有没有更痛苦的方法来做到这一点?我只下载了 20 张图片以供以后在应用程序中使用,并且它会立即将其锁定。

它可能不相关,但这就是我在 iPhone 版本的 Obj-C 中实现它的方式。

for( NSDictionary *exhibitor in exhibitors )
{
    [self performSelectorInBackground:@selector(downloadExhibitorImage:) withObject:exhibitor];
}
4

1 回答 1

3

看看DownloadManager并作为AsyncTask的替代方案

于 2011-07-05T21:35:11.473 回答