android通过电子邮件附件发送公共存储文件

时间:2017-11-19 00:24:13

标签: android email-attachments

这是我之前发布的帖子1的后续内容。

总结一下,我希望MyApp使用Intent将其数据文件发送到指定的电子邮件地址。我现在有以下代码:

public void onClickSend(View v) {
    Intent i = new Intent(android.content.Intent.ACTION_SEND);
    String Email[] = { "my.address@gmail.com" };
    i.putExtra(android.content.Intent.EXTRA_EMAIL, Email);
    i.putExtra(android.content.Intent.EXTRA_SUBJECT, "Report");
    i.setType("text/plain");

    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
    File f = new File(path, _tdSource.GetFileName());

    Uri sUri = FileProvider.getUriForFile(v.getContext(), "org.myorg.myapp.fileprovider", f);
    i.setData(sUri);
    i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    i.putExtra(Intent.EXTRA_STREAM, sUri);
    startActivity(i);
}

MyApp的清单文件包含以下内容:

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:theme="@style/AppTheme">
    ...
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SubActivity"></activity>
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="org.myorg.myapp.fileprovider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>
</application>

MyApp在调用FileProvider.getUriForFile()时遇到异常。奇怪的是,异常是java.lang.reflect.InvocationTargetException并且在AppCompatViewInflater.onClick()中被捕获。

我不知道我做错了什么或者去哪了...

1 个答案:

答案 0 :(得分:1)

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, address);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); // attachment
intent.setType("message/rfc822"); // message content type
startActivity(Intent.createChooser(intent, "Share via");