Android display images when offline once downloaded using fresco

荒凉一梦 提交于 2019-12-13 09:24:19

问题


I want fresco to download and save images to sd-card when connected to internet. Later when offline and even if cache is cleared, still I need fresco to show saved images. Is this possible? If yes, how?

Simply saving images to disk cache doesnt seem to work when cache is cleared.


回答1:


Fresco caches images for you. If you are offline, the images should still be displayed. You should not need to do anything.

However, when the cache is cleared (e.g. when the user presses the button or when device space is low), images are obviously deleted from the cache - which is the desired behavior that should not be changed.

There are 2 options: save selected items, move the cache

Save selected items

If you want to persist selected images (e.g. a "Save" button), you can get the encoded image and save it somewhere on the device. You should not do this for all images since they will be on the disk 2 times and clearing the cache / uninstalling the app will leave 1 copy on the device.

Something like this could work:

DataSource<CloseableReference<PooledByteBuffer>>
    dataSource = Fresco.getImagePipeline().fetchEncodedImage(imageRequest, callerContext);
dataSource.subscribe(new BaseDataSubscriber<CloseableReference<PooledByteBuffer>>() {
  @Override
  protected void onNewResultImpl(DataSource<CloseableReference<PooledByteBuffer>> dataSource) {
    CloseableReference<PooledByteBuffer> encodedImage = dataSource.getResult();
    if (encodedImage != null) {
      try {
        // save the encoded image in the PooledByteBuffer
      } finally {
        CloseableReference.closeSafely(encodedImage);
      }
    }
  }

  @Override
  protected void onFailureImpl(DataSource<CloseableReference<PooledByteBuffer>> dataSource) {
    // something went wrong
  }
}, executorService);

}

More information on how to use the pipeline to get the encoded image: http://frescolib.org/docs/using-image-pipeline.html

Move the cache

Keep in mind that this will persist the cache when it is moved to an external directory, so be careful since this will leave files when the app is uninstalled.

Fresco also allows you to supply a custom DiskCacheConfig and you can create a new DiskCacheConfig.Builder and call setBaseDirectoryPath(File) to change the path to a different folder (e.g. one on the SD card) and you can also change the directory name with setBaseDirectoryName(String)

More information on how Fresco does caching: http://frescolib.org/docs/caching.html




回答2:


You need to manually save the images to disk when downloaded. When displaying the images, check if image is in disk: if its not, download from url (and save to disk).



来源:https://stackoverflow.com/questions/40484538/android-display-images-when-offline-once-downloaded-using-fresco

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!