在我的应用程序中,用户可以在聊天中发送任何类型的文件(图像、视频、文档等)。单击带有文件的消息时,必须在另一个应用程序中打开该文件。使用下面的代码,我可以生成内容 uri 并将其发送到其他应用程序,但其他应用程序无法读取它们。我该怎么做才能让其他应用程序读取文件而不会出错?
内容 uri:
content://com.my.app.provider/external_files/Messages/Documents/Hello%20World.docx
功能:
fun openFile(file: File) {
val path = FileProvider.getUriForFile(this, applicationContext.packageName + ".provider", file)
Log.i(TAG, "$path ")
val intent = Intent(Intent.ACTION_VIEW)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
intent.setDataAndType(path, file.mimeType())
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
e.printStackTrace()
}
}
提供者:
<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/file_paths" />
</provider>
文件路径.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>