In this post, we will learn how to share the files in Android using the Intent. Android allows us to share the content with intent, this can be done by using Implicit intent. It uses the action ACTION_SEND, it will communicate with other applications to share the content using the URI of the files.
Before proceed, what is intent in Android?
Intent – in Android Intent is a message object that is used to communicate between different components, like Activities, Broadcast receiver, Content Providers, and Services.
There are two types of intent available in Android, one is Implicit Intent and another one is Explicit Intent. The first one ‘Implicit Intent’ doesn’t specify the component but it provides the information of available components provided by the system that is best to run for that.
The Explicit Intent is the one that runs the specific component or the class, it is mostly used to run the different internal activities.
How to share the files in Android
To share the files in Android we have to do the following steps.
First set the permission in the AndroidManifest file, as followed. Also, you need to add a permission request handler to get storage access for the application. You can find the article for creating a Permission handler for storage and other types.
Create the file path for your Android application, in res->xml
folder. Please include the paths you want to access, here I have included all the file paths for a typical application.
The above lines will tell the available paths to the application, you can add/remove them as you need. I have added all possible file paths in this code.
Now set up the provider in the AndroidManifest file as below. Add these lines inside the activity blocks.
The Manifest file setup is done, let’s implement the sharing intent handling in your Activity or the Fragment. Do the following in your project.
First create a file from the path which have to be shared, then get the content URI of the file using FileProvider. Check for the availability of the Content for null. If the content URI is valid then invoke Share intent bythe following method.
Output
While calling the share method as mentioned above you will see a file-sharing chooser. This will list the available applications for sharing the given mime-type
.
Similarly, you can use the same way to share different content with external applications. Happy Coding!