【发布时间】: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