Android – 纠正multithreading

有人可以帮我一下这张图片下载代码吗? 我希望它在后台运行,但似乎新的Thread(新的Runnable())肯定不是要走的路,根据Android 文档 ,我不知道如何处理这个问题:

// 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个图像,以便稍后在应用程序中使用,并立即将其锁定。

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

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

看一下DownloadManager,并作为AsyncTask的替代方案

请查看http://code.google.com/p/libs-for-android/wiki/ImageLoader