You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Android中Uri类型转换及OnReceiveValue回调报错问题

问题描述

在Visual Studio 2022中使用Xamarin开发Android应用时,在OnActivityResult方法中处理文件选择结果,执行以下代码:

mUploadMessage.OnReceiveValue(new Uri[] { result });

出现编译错误:Error CS0029 Cannot implicitly convert type 'Android.Net.Uri' to 'System.Uri'。

尝试的转换方式及对应报错

  • 强制转换:

    mUploadMessage.OnReceiveValue(new Uri[] { (Uri)result });
    

    报错:Error CS0030 Cannot convert type 'Android.Net.Uri' to 'System.Uri'

  • as关键字转换:

    mUploadMessage.OnReceiveValue(new Uri[] { result as Uri });
    

    报错:Error CS0039 Cannot convert type 'Android.Net.Uri' to 'System.Uri' via a reference conversion...

  • 字符串中转转换:

    Android.Net.Uri result = intent.Data;
    String urlResult = result.ToString();
    Uri sysUrl = new System.Uri(urlResult);
    mUploadMessage.OnReceiveValue(new Uri[] { sysUrl });
    

    报错:Error CS1503 Argument 1: cannot convert from 'System.Uri[]' to 'Java.Lang.Object?'

  • 直接传入字符串:

    Android.Net.Uri result = intent.Data;
    String urlResult = result.ToString();
    mUploadMessage.OnReceiveValue(urlResult);
    

    编译通过,但运行时抛出异常:Java.Lang.ClassCastException Message=java.lang.String cannot be cast to android.net.Uri[]

  • 直接传入Android.Net.Uri对象:

    Android.Net.Uri result = intent.Data;
    mUploadMessage.OnReceiveValue(result);
    

    运行时报错:Java.Lang.ClassCastException Message=android.net.Uri$HierarchicalUri cannot be cast to android.net.Uri[]

解决方案

问题核心是IValueCallback.OnReceiveValue要求接收Android.Net.Uri数组,但代码中因命名空间默认引用System,导致Uri被解析为System.Uri,同时参数类型不匹配。

正确修改代码

在创建数组时明确指定Android.Net.Uri命名空间,确保传递的是符合要求的数组参数:

protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
    if (requestCode == FILECHOOSER_RESULTCODE)
    {
        if (null == mUploadMessage) return;
        
        Android.Net.Uri result = intent.Data;
        // 明确创建Android.Net.Uri类型的数组
        mUploadMessage.OnReceiveValue(new Android.Net.Uri[] { result });
        mUploadMessage = null;
    }
}

额外注意事项

  • 检查代码中是否存在using Uri = System.Uri;这类别名定义,避免命名空间冲突。
  • 若需兼容API 21及以上版本,可扩展处理IValueCallback<Android.Net.Uri[]>的情况,但当前场景下上述修改已能解决问题。

内容的提问来源于stack exchange,提问作者markj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:20:31