Android 内容 Uri 无法被其他应用播放

问题描述

我使用下载管理器将文件下载到外部存储。 我使用

将目的地设置为下载文件
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName)

成功后我用

检索uri
val fileUri=cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))

这给了我这个

file:///storage/emulated/0/Download/dishapatani_Jan%2007%2C%2008%3A07_1609986166669.mp4

现在我尝试使用 Intent 播放此视频文件

  val uri=Uri.parse(" file:///storage/emulated/0/Download/dishapatani_Jan%2007%2C%2008%3A07_1609986166669.mp4")
        val intent = Intent()
        intent.action = Intent.ACTION_VIEW
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        val contentUri = FileProvider.getUriForFile(requireContext(),requireContext().packageName + ".provider",File(localUri))

        intent.setDataAndType(contentUri,"video/mp4")
        intent.setData(contentUri)
        startActivity(intent)

这里的内容 Uri 是 content://com.myapp.provider/external_path/dishapatani_Jan%252007%252C%252008%253A07_1609986166669.mp4

但是当我使用 action_share Intent 时,它既没有播放也没有被其他应用识别。

还必须删除具有 file:// 的文件 uri 并替换为 /storage/emulated/0/Download/dishapatani_Jan%2007%2C%2008%3A07_1609986166669.mp4" 否则应用崩溃,说没有配置 root。

这是我的提供者路径

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_path" path="/Download" />
</paths>

和清单

 <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>

解决方法

不要乱用路径和地址以及您自己的文件提供程序。

您从下载管理器获得 - 或者可以获得 - URI。

用它来播放文件。