Может ли кто-нибудь помочь мне с этим кодом загрузки изображения?Я хочу, чтобы он работал в фоновом режиме, но похоже, что новый поток (новый Runnable ()) определенно не подходит, согласно Android docs , и я не уверен, как ещеподход к этому:
// 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];
}