[英]How can I share pdf file in android?
I try to share a pdf file from android/data/mypackage/files/file.pdf I generate these pdfs also in this app, and when I try to share it, the pdf doesn't appear in on attached files from email, or google drive says something like: "No data to share".我尝试从 android/data/mypackage/files/file.pdf 共享一个 pdf 文件我也在这个应用程序中生成这些 pdf,当我尝试共享它时,pdf 没有出现在 email 的附加文件中,或者谷歌驱动器说:“没有数据共享”。 Here is my code for sharing pdf:
下面是我分享的代码pdf:
val aName = intent.getStringExtra("iName")
val file = File(this.getExternalFilesDir(null)?.absolutePath.toString(), "$aName")
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.putExtra(Intent.EXTRA_STREAM, file)
shareIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
shareIntent.type = "application/pdf"
startActivity(Intent.createChooser(shareIntent, "share.."))
Toast.makeText(this,"$file",Toast.LENGTH_SHORT).show()
The pdf path looks correct when I toast it: pdf 路径在我敬酒时看起来是正确的:
The problem is that you are not using a URI, just sending a path, you need several things.问题是你没有使用 URI,只是发送路径,你需要几样东西。
Provider paths提供商路径
You have to create provider_paths.xml
under xml
folder in res
:您必须在
res
中的xml
文件夹下创建provider_paths.xml
:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path
name="files_root"
path="/" />
</paths>
Set the provider in the Manifest
under Aplication
:在
Aplication
下的Manifest
中设置提供者:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
Get the URI获取 URI
fun uriFromFile(context:Context, file:File):Uri {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
{
return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file)
}
else
{
return Uri.fromFile(file)
}
}
Your final code:你的最终代码:
val aName = intent.getStringExtra("iName")
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.putExtra(Intent.EXTRA_STREAM, uriFromFile(context,File(this.getExternalFilesDir(null)?.absolutePath.toString(), "$aName")))
shareIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
shareIntent.type = "application/pdf"
startActivity(Intent.createChooser(shareIntent, "share.."))
I didn't test the code, write it from "memory", let me know if it works for you.我没有测试代码,是从“记忆”中写的,让我知道它是否适合你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.