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];
}