Search code examples
androidandroid-contentprovider

How to use a ContentProvider with DiskLruCache in Android


In my Android app, I would like to cache images on disk that will then be displayed in a WebView, for which I need to access files by some kind of path or URI. (In order to use <img src="..">.) All caching implementations I found provide no access to the absolute file paths, but rather return InputStreams or Bitmap objects.

Is it possible to implement a ContentProvider that I can use to turn Bitmap objects into something file like by having <img src="content://my/image.png"> in my WebView?


Solution

  • override ContentProvider#openFile(Uri uri, String mode), if your content is in-memory cached data and you cannot return ParcelFileDescriptor#open(File file, int mode), ParcelFileDescriptor#fromFd(int fd) or ParcelFileDescriptor#fromSocket(Socket socket) use a helper method ContentProvider#openFileHelper(Uri uri, String mode) or use ParcelFileDescriptor#createPipe() and implement your custom producer part