如何解决直接将图像从 Android 图库共享到我的 flutter 应用程序时收到的奇怪且不完整的 Uri 和路径

Sou*_*wat 14 android kotlin flutter asus flutter-android

我在 Kotlin 中为 flutter 应用程序编写了一个功能,可以将媒体文件直接从 Android 手机图库共享到应用程序。

在我测试过的许多设备上运行良好,例如 Realme 3 Pro、Oneplus 6t、三星 m40。

但是,在Asus Zenfone Max Pro M2共享任何媒体文件时,都会收到奇怪且不完整的信息URI&path

来自 Kotlin 代码的日志

D/URI =====(26032) : content://com.android.providers.downloads.documents/document/624

D/路径 =====(26032): /document/624

Kotlin 代码

override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    this.binding = binding
    binding.addOnNewIntentListener(this)
    handleIntent(binding.activity.intent, true)
}
----------------------------------------------------------------------
private fun handleIntent(intent: Intent, initial: Boolean) {
    when {
        (intent.type?.startsWith("text") != true)
                && (intent.action == Intent.ACTION_SEND
                || intent.action == Intent.ACTION_SEND_MULTIPLE) -> { // Sharing images or videos

            val value = getMediaUris(intent)
            if (initial) initialMedia = value
            latestMedia = value
            eventSinkMedia?.success(latestMedia?.toString())
        }
...
----------------------------------------------------------------------
private fun getMediaUris(intent: Intent?): JSONArray? {
    if (intent == null) return null

    return when (intent.action) {
        Intent.ACTION_SEND -> {
            val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
            Log.d("URI =====",uri)
            val path = uri?.let{ FileDirectory.getPathFromUri(applicationContext, it) } ?: uri?.path
            Log.d("Path =====",path)
            if (path != null) {
...
Run Code Online (Sandbox Code Playgroud)

设备信息

Device Name: Asus Zenfone Max Pro M2
Android Version: 9
External SD card: present
Run Code Online (Sandbox Code Playgroud)

如何解析此 URI 并获取包含文件名和扩展名的正确路径?

Oma*_*att 0

您可以使用uri_to_file插件从 中获取路径content://uri。使用时,只需解析 uri 并使用toFile(uri)

import 'package:uri_to_file/uri_to_file.dart';

try {
  String uriPath = 'content://com.android.providers.downloads.documents/document/624';
  Uri uri = Uri.parse(uriPath);
  File file = await toFile(uri);
} catch (e) {
  debugPrint(e);
}
Run Code Online (Sandbox Code Playgroud)