9

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

在我测试过的许多设备上运行良好,例如 Realme 3 Pro、Oneplus 6t、Samsung 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) {
...

设备信息

Device Name: Asus Zenfone Max Pro M2
Android Version: 9
External SD card: present

如何解析此 URI 并获得带有文件名和扩展名的正确路径?

4

1 回答 1

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);
}
于 2022-02-12T07:19:52.900 回答