Using Android FileProvider for sharing files

Recently, I was making an android app and needed to implement a function that allows the user to attach a text file to gmail. Everything seemed so simple. But I found myself unable to find the solution. It took nearly 24hours searching over the web and finally found the solution. What was the solution ? It is called the  FileProvider! Did I manage to solve the problem? Actually, FileProvider was new to me, therefore, it took quite some time to implement the logic. Nevertheless, I was able to accomplish what I needed to do!


Heres a sample code for saving text file and attaching file to the gmail application

1.Let’s start by¬†preparing the basics for the provider in manifest.xml

First we will have to add the following code in the middle of the application tag.

By the way what is “com.myapp.AlteredWebSite”? It is a class that will be using the FileProvider. Check out the following link to learn more about FileProvider

    android:grantUriPermissions="true" >
        android:resource="@xml/my_paths" />

2. Create the string of path that you will be using it along with the FileProvider

<paths xmlns:android="">
    <files-path name="files" path="." />

3. Now let’s create a method for saving the textFile

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(this.getFilesDir(),"files");

        if (!root.exists()) {
        File gpxfile = new File(root, sFileName);
        android.util.Log.d("Test","gpx "+root.toString());
        FileWriter writer = new FileWriter(gpxfile);
    } catch (IOException e) {

4. Create the method for attaching the text file to the gmail.

private void sendEmail() {
    final String auth = "com.myapp.AlteredWebSite"
    File imagePath = new File(getFilesDir(), "files");
    File newFile = new File(imagePath, mFileName);
    Uri contentUri = FileProvider.getUriForFile(this,auth, newFile);

    Intent intent = new Intent(android.content.Intent.ACTION_SEND);
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
    String to[] = { "mail" };
    intent.putExtra(Intent.EXTRA_EMAIL, to);
    intent.putExtra(Intent.EXTRA_STREAM, contentUri);

Leave a Reply

Your email address will not be published. Required fields are marked *