Sharing a file
In this example you'll learn how to share a file with other apps. We'll use a pdf file in this example although the code works with every other format as well.
Specify the directories in which the files you want to share are placed
To share files we'll use a FileProvider, a class allowing secure file sharing between apps. A FileProvider can only share files in predefined directories, so let's define these.
Create a new XML file that will contain the paths, e.g. res/xml/filepaths.xml
Add the paths
Define a FileProvider and link it with the file pathsThis is done in the manifest:
Generate the URI for the fileTo share the file we must provide an identifier for the file. This is done by using a URI (Uniform Resource Identifier).
As you can see in the code we first make a new File class representing the file. To get a URI we ask FileProvider to get us one. The second argument is important: it passes the authority of a FileProvider. It must be equal to the authority of the FileProvider defined in the manifest.
Share the file with other appsWe use ShareCompat to share the file with other apps:
A chooser is a menu from which the user can choose with which app he/she wants to share the file. The flag Intent.FLAG_GRANT_READ_URI_PERMISSION is needed to grant temporary read access permission to the URI.