【问题标题】:Android - Correct MultithreadingAndroid - 正确的多线程
【发布时间】:2011-07-05 21:24:08
【问题描述】:

有人可以帮我看看这个图片下载代码吗?我希望它在后台运行,但根据 Android docs,似乎 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];
}

【问题讨论】:

    标签: java android multithreading download runnable


    【解决方案1】:

    查看DownloadManagerAsyncTask 作为替代方案

    【讨论】:

    • 看起来只有 SDK 9、2.3 及更高版本才有,对吧?有2.2的方式吗?
    • 这就是我添加 AsyncTask 的原因......当然它不太方便
    • 是的,我遇到了那个混蛋,你有什么建议可以整合我的电话吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多