Android - Correct Multithreading

对着背影说爱祢 提交于 2019-12-09 14:07:12

问题


Can someone please give me a hand with this image downloading code? I want it to run in the background, but it seems like new Thread(new Runnable()) is definitely not the way to go, according to the Android docs, and I'm not sure how else to approach this:

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

}

Is there a less painful way of doing this? I'm only downloading like 20 images to use later in the app, and it is locking it up right away.

It may not be relevant, but this is how I am achieving it in Obj-C for the iPhone version.

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

回答1:


Take a look at the DownloadManager and as an alternative at AsyncTask




回答2:


Take a look at http://code.google.com/p/libs-for-android/wiki/ImageLoader



来源:https://stackoverflow.com/questions/6589051/android-correct-multithreading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!