Android App Dev - Download only once for displaying image
I currently use the code below to download and then display an image, and I was just hoping someone could show me how to check if the file was already downloaded and just show if so, else then download and show.. Please help.
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tr开发者_Go百科y {
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bmImg = BitmapFactory.decodeStream(is);
ImageView imView = (ImageView)findViewById(R.id.imview);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File imageIamInterestedIn = new File( filePath );
if (!imageIamInterestedIn.exists())
{
download();
}
else
{
imageView.setImageBitMap( BitmapFactory.decodeFile( filePath ) );
}
You need to write a cache somehow, either a temporary memory cache, or a persistent database/file cache.
Here is some steps to achieve what you want:
- Someone requests to view an image on their device.
- Check your cache (either memory or persistent as mentioned above).
- If it exists there, return that, otherwise fetch the image using your code.
A persistent cache would be desirable if you don't want to ever have to fetch this image again, because you will access this image often in the future. A temporary memory cache would be desirable if speed is a concern, and you will not be accessing this image very much in the future.
Just download this LazyLoader: http://open-pim.com/tmp/LazyList.zip.
Then there is a ImageLoader class which may be helpful to you for the same task you have mentioned above.
For more info: Lazy load of images in ListView, it is for listview but you can use the same for loading images asynchronously.
精彩评论