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

https://developer.android.com/reference/android/support/v4/content/FileProvider.html

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

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

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="files" path="." />
</paths>

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()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        android.util.Log.d("Test","gpx "+root.toString());
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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.setType("application/octet-stream");
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "subject");
    String to[] = { "mail" };
    intent.putExtra(Intent.EXTRA_EMAIL, to);
    intent.putExtra(Intent.EXTRA_TEXT,text);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.putExtra(Intent.EXTRA_STREAM, contentUri);
}

Leave a Reply

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