A lot of Android apps make viewing images a core part of their user experience. Many of these apps use image caching libraries, like Glide, to make image caching easy, robust, and configurable. Sharing these cached images can be a bit tricky. A few questions arose when I tried:

How do I access files in the cache?

Do other apps have access to these files?

What are the needed permissions if I need to manually copy the file somewhere else?

Those are just a few of the questions that came up, each with a pretty simple answer. A first pass at sharing images in my cache involved, re-caching the image to a public directory (ie. root of the external storage device), generating a URI, and passing that URI to an Intent to share with other apps. This sounds simple, but it is complicated by the fact that I needed to ask the user for permission to read and write to the external storage on their device, if they were running Android 6.0 Marshmallow or above. This flow worked, but I was looking for something much simpler for the user and myself, the developer. Enter the FileProvider.

The FileProvider API

The FileProvider API, added to the Android Support libraries in version 22.0.0, is a ContentProvider-like API that allows URI specific sharing of files relevant to your application. It can, temporarily, enable access (read and/or write) to the file at the URI. You also do not need to copy the file to a more accessible location on the user’s device. Setting up the FileProvider is very straightforward.

Setting up a File Provider

Setting up the FileProvider is a three step process.

First, like we would do with a ContentProvider, we added a <provider> entry to our AndroidManifest.xml file.



<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.yourdomain.android.fileprovider" android:grantUriPermissions="true" android:exported="false"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/filepaths" /> </provider>

This provider entry has a <meta-data> element that points to an XML file, that defines what paths, within our application file structure, we want to expose with our FileProvider. This is important. You can only share files in the paths contained in this XML file. I created an XML file in the “res/xml” folder.

<paths> <external-files-path name="image_files" path="." /> </paths>

In my particular instance, I am caching images to the External Files directory (which can be located on the SD card or a portion of internal memory, simulating an SD Card). Other tags you can use here:

<files-path> , corresponding to , corresponding to Context.getFilesDir()

<cache-path> , corresponding to , corresponding to Context.getCacheDir()

<external-path> , corresponding to , corresponding to Context.getExternalStorageDirectory()

<external-cache-path>, corresponding to , corresponding to Context.getExternalCacheDir()

The name attribute is a string that will be used as a URI-path component in the URI that’s generated by FileProvider. The path attribute, is the relative path to folder containing the files you would like share. In my case, I’m fine with sharing the root because it only contains cached images, but you should probably be as granular as possible in the case where you have multiple directories or file types in this directory.

Now that my FileProvider is set up and configured, how do I share files out of my cache.

Sharing Cached Files

The specifics on sharing cached image files is highly dependant on the Image caching library used and how it’s configured. At a high level, the process is:

Cache an image to a location (done by an image caching library) that falls in the location specified in XML configuration file given to the FileProvider. Get a reference to that cached image using the java.io.File API. Pass the File reference to FileProvider.getUriForFile() to get a URI you can pass to other apps. Pack that URI into an Android Intent to start sharing with other apps.

Very straightforward. Now this is how I did it with Glide.

My first step was to specify a location for Glide to store cached images. I needed to subclass DiskLruCacheFactory to make this happen (Note: you don’t need to subclass DiskLruCacheFactory if you want to use the Cache directory).

private static class DiskCacheFactory extends DiskLruCacheFactory { DiskCacheFactory(final Context context, final String diskCacheName, long diskCacheSize) { super(new CacheDirectoryGetter() { File cacheDirectory = new File(context.getExternalFilesDir(null), diskCacheName); return cacheDirectory; }, (int) diskCacheSize); } }

As you can see from the code snippet, I pass in a reference to the External Files directory. By default, Glide uses the Cache directory.

I implement a GlideModule so that I can customize caching behavior in my application. I specify my subclassed DiskLruCacheFactory class in my GlideModule.

public class MyGlideModule implements GlideModule { private static final int IMAGE_CACHE_SIZE = 200_000_000; @Override public void applyOptions(Context context, GlideBuilder builder) { builder.setDiskCache(new DiskCacheFactory(context, “.”, IMAGE_CACHE_SIZE)); } @Override public void registerComponents(Context context, Glide glide) { // ... } }

Now, I instruct Glide where it can find my GlideModule by adding a <meta-data> tag to the AndroidManifest.xml file, in <application> element.

<meta-data android:name="com.yourdomain.android.MyGlideModule" android:value="GlideModule"/>

Next, I invoke a manual file caching with Glide.

File file = Glide.with(context) .load(uri) // uri to the location on the web where the image originates .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) .get();

This is specific to Glide and worth mentioning. When Glide caches a file to disk, the file name is comprised of generated key with an integer appended to it. There is no extension. This is important because sharing an extension-less image will make it difficult for the apps you are sharing with to determine how this file should be handled (despite the MIME type being sent along with the image in the Intent).

I worked around this issue by simply copying that file, appending an extension to the duplicate in the process. Since I know I am always handling JPEGs, I give these files the “.jpg” extension. This may not work in cases where you may be dealing with different types of images like, GIFs, PNGs, WebP, etc.

Finally, I can get a URI from the FileProvider for my cached image by calling FileProvider.getUriForFile().

// be sure to use the authority given to your FileProvider in the AndroidManifest.xml file String authority = “com.yourdomain.android.fileprovider”; Uri uri = FileProvider.getUriForFile(context, authority, file); Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.setType("image/jpeg"); context.startActivity(Intent.createChooser(intent, “Share via”);

The Uri generated by the FileProvider looks like:

content://com.yourdomain.android.fileprovider/external_files/bb65e6a364264255b4833d34e____some_key.0.jpg

Once the Intent makes its way to the target app, things should look just like you are sharing a picture you’ve just taken.

#Dassit