开发者

Android App Dev - Download only once for displaying image

开发者 https://www.devze.com 2023-03-06 11:57 出处:网络
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 downloa

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:

  1. Someone requests to view an image on their device.
  2. Check your cache (either memory or persistent as mentioned above).
  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消