And*_*cre 1 pdf android share kotlin android-implicit-intent
我尝试从 android/data/mypackage/files/file.pdf 共享 pdf 文件我也在这个应用程序中生成这些 pdf,当我尝试共享它时,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()
Run Code Online (Sandbox Code Playgroud)
问题是你没有使用 URI,只是发送一个路径,你需要几件事。
提供者路径
您必须在provider_paths.xml以下xml文件夹中创建res:
<?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>
Run Code Online (Sandbox Code Playgroud)
Manifest在下设置提供程序Aplication:
<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>
Run Code Online (Sandbox Code Playgroud)
获取 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)
}
}
Run Code Online (Sandbox Code Playgroud)
您的最终代码:
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.."))
Run Code Online (Sandbox Code Playgroud)
我没有测试代码,从“记忆”中编写它,让我知道它是否适合您。