gpt4 book ai didi

android - kotlin 发送带附件的电子邮件因 URI 失败

转载 作者:行者123 更新时间:2023-11-30 00:03:43 24 4
gpt4 key购买 nike

我有以下 kotlin 代码来发送带附件的电子邮件:

val file = File(directory, filename)
file.createNewFile()
file.writeText("My Text", Charsets.UTF_8)
// ---- file is written succesfully, now let us
// try to get the URI and pass it for the intent

val fileURI = FileProvider.getUriForFile(this, "com.mydomain.myapp", file!!)

val emailIntent = Intent(Intent.ACTION_SEND).apply {
putExtra(Intent.EXTRA_SUBJECT, "My subject"))
putExtra(Intent.EXTRA_TEXT, "My message")
putExtra(Intent.EXTRA_STREAM, fileURI)
}
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.type = "text/plain"
startActivity(emailIntent)

现在,当我运行上面的代码时,出现错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

为 fileURI 赋值行。如果不是 FileProvider,如果我使用:

putExtra(Intent.EXTRA_STREAM, file!!.toURI())

作为额外的 Intent 参数,然后我得到一个错误:

W/Bundle: Key android.intent.extra.STREAM expected Parcelable but value was a java.net.URI.  The default value <null> was returned.

03-22 11:39:06.625 9620-9620/com.secretsapp.secretsapp W/Bundle:尝试转换生成的内部异常:

W/Bundle: Key android.intent.extra.STREAM expected Parcelable but value was a java.net.URI.  The default value <null> was returned.
W/Bundle: Attempt to cast generated internal exception:
java.lang.ClassCastException: java.net.URI cannot be cast to android.os.Parcelable
at android.os.Bundle.getParcelable(Bundle.java:945)

该文件是在全局 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) 目录下的子目录下创建的,该应用程序也具有 Manifest.permission.WRITE_EXTERNAL_STORAGE 权限。关于如何获取文件的 URI 并将其附加到电子邮件 Intent 的任何指示?

最佳答案

对于您的第一次尝试 — 这是正确的方法 — 您的 <provider>没有权限值 com.mydomain.myapp . <provider> 中的权限字符串 list 中的元素必须与您传递给 getUriForFile() 的第二个参数匹配.这包含在 the documentation for FileProvider 中.

第二次尝试,toURI()返回 URI , 不是 Uri .虽然您可以将其切换为 Uri.fromFile() ,一旦你的 targetSdkVersion 就会在 Android 7.0+ 上崩溃攀升至 24 或更高。使用 FileProvider方法。

关于android - kotlin 发送带附件的电子邮件因 URI 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49427836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com