java - 如何捕获图像并通过电子邮件将其 Uri 直接发送到附件
问题描述
我有 Ui,我必须在其中捕获图像和 onActivityResult 我必须将其直接发送到电子邮件,因为我已经尝试了堆栈上的所有可能解决方案,但每次都失败并且它给我无法附加错误,经过很长时间搜索和实施的时间我发现了一些要检查的东西,如果我可以读取文件或者不是这样file.canRead()
,它总是给我错误的。任何解决方案将不胜感激。
private fun sendEmail(liscence: String, desc: String) {`<br>
val emailIntent = Intent(Intent.ACTION_SEND)`<br>
val to = arrayOf("info@gmail.com")`<br>
emailIntent.putExtra(Intent.EXTRA_EMAIL, to)`
emailIntent.type = "text/plain";
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
// attachment Uri comes through camera
emailIntent.putExtra(Intent.EXTRA_STREAM, imagePath)
// the mail subject
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Report")
//email body
val body = "${liscence} \n ${desc}"
emailIntent.putExtra(Intent.EXTRA_TEXT, body)
//need this to prompts email client only
emailIntent.type = "message/rfc822";
startActivity(Intent.createChooser(emailIntent, "Send email using..."))
}
解决方案
这里经过大量研究,我在Android文档中找到了解决方案
https://developer.android.com/reference/android/support/v4/content/FileProvider.html#GetUri
这是我将捕获的图像共享到 Gmail 的最终代码。
此代码将直接转到 Manifest 文件,您必须将权限用作有效的权限提供者。
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="android:authorities">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/picker_provider_paths" />
</provider>
提供者的 XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="image_picked" path="picked/"/>
<external-path name="*" path="Pictures/"/>
</paths>
将图像作为附件发送的函数。
private fun sendEmail() {
val contentUri =
FileProvider.getUriForFile(context!!,
"yourPackageAndThen.com.mydomain.fileprovider",
File(PATH OF IMAGE or FILE ));
val emailIntent = Intent(Intent.ACTION_SEND)
//need this to prompts email client only
emailIntent.type = "message/rfc822";
val to = arrayOf("EMAIL ID TO SEND")
emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
// attachment Uri comes through camera
emailIntent.putExtra(Intent.EXTRA_STREAM, contentUri)
// the mail subject
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Report")
//email body
emailIntent.putExtra(Intent.EXTRA_TEXT, MESSAGEforBody)
startActivity(Intent.createChooser(emailIntent, "Send email using..."))
}
推荐阅读
- python - 当工作表有多个可能的名称时,如何将多个 Excel 工作表读入 python
- javascript - 如何在 PrimeNG 的下拉输入字段中显示来自 api 的一些值
- python - 测量将整数附加到大型列表字典的效率
- scala - 从 df 中删除 n+1 行
- sql - Pivot 不适用于聚合 clob 列
- powerbi - 当用户使用 AD 帐户从 Power BI 服务门户登录时,我们如何在雪花数据库中获取用户名
- java - 如何创建创建 PKCS12 密钥库?
- c# - 将新行添加到 RadGridView - WPF 时如何防止 RowValidating 事件
- python - 运行 pyinstaller 应用程序时无法启动循环
- java - 重新启动 Java 应用程序时重用 Selenium WebDriver 会话