Problem Attaching internal file to GMail in my android app

前端 未结 3 1048
逝去的感伤
逝去的感伤 2020-12-19 23:44

My app writes data to text files (on sd card and internal memory). Later the app emails the text files to a list of people. I am having trouble getting gmail to attach a fil

相关标签:
3条回答
  • 2020-12-20 00:23

    Like Dhego, I used a content provider. Specifically, a FileProvider.

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

    Using this only requires that you modify your Manifest and create an additional resource file. Also, you will need to obtain a validly formatted URI via a static method provided by FileProvider.

    In your Manfiest:

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

    The "com.example.authority.fileprovider" is your application authority with "fileprovider" appended.

    In the res/xml folder, create a file_paths.xml file that contains the paths to the files you want to expose. In my case, I was exposing them from the application cache directory, so my XML looks like:

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

    In my case, "reports" is a folder within the application cache directory that I am writing files to.

    The last thing to do is in your code:

    1. Write files you want to expose to the folders and storage areas specified in file_paths.xml.
    2. Generate a valid URI to set on the Intent you will invoke for sending an email (Intent.ACTION_SEND).

    Here's some sample code:

    emailIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(getActivity(), "com.example.authority.fileprovider", fileToAttach));
    

    Invoke startActivity on your Intent and that should be it!

    0 讨论(0)
  • 2020-12-20 00:26

    It appears that there is indeed an issue with gmail. Unfortunately however, at the time of the writing it seems it hasn't been fixed.

    0 讨论(0)
  • 2020-12-20 00:34

    the only way I found around this was to make my own content provider and pass in the uri to my content provider as the attachment.

    0 讨论(0)
提交回复
热议问题