gpt4 book ai didi

java - Android - 正确的多线程

转载 作者:行者123 更新时间:2023-11-29 03:55:33 26 4
gpt4 key购买 nike

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

最佳答案

看看 DownloadManager作为替代方案,请访问 AsyncTask

关于java - Android - 正确的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6589051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com