惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
SecWiki News
SecWiki News
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - 【当耐特】
Martin Fowler
Martin Fowler
宝玉的分享
宝玉的分享
F
Fortinet All Blogs
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
aimingoo的专栏
aimingoo的专栏
V
V2EX
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
O
OpenAI News
T
Troy Hunt's Blog
TaoSecurity Blog
TaoSecurity Blog
小众软件
小众软件
MongoDB | Blog
MongoDB | Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
LINUX DO - 最新话题
N
News | PayPal Newsroom
PCI Perspectives
PCI Perspectives
Engineering at Meta
Engineering at Meta
美团技术团队
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
V
Vulnerabilities – Threatpost
B
Blog RSS Feed
NISL@THU
NISL@THU
Security Latest
Security Latest
The Register - Security
The Register - Security
酷 壳 – CoolShell
酷 壳 – CoolShell
The GitHub Blog
The GitHub Blog
S
SegmentFault 最新的问题
N
News and Events Feed by Topic
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Schneier on Security
罗磊的独立博客
Know Your Adversary
Know Your Adversary
Hacker News: Ask HN
Hacker News: Ask HN
S
Security Affairs
月光博客
月光博客
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

博客园 - hyamw

【转】代码审查工具fisheye/crucible安装及破解 Win11单语言系统添加美式键盘的方法 CentOS下安装dotnet tools工具报错 (转)支持 PS/2 与 USB 的键盘过滤驱动(可卸载) Unity编辑器扩展-Custom List, displaying data your way 值得推荐的C/C++框架和库 (真的很强大)〔转〕 SIGGRAPH2016【转】 在64位windows下使用instsrv.exe和srvany.exe创建windows服务[转] VS2015调试UWP程序时提示错误DEP0700 : Registration of the app failed. Another user has already installed Unity 4.x Asset Bundle 重名 VC++ Debugger Tips[转] centos下postgresql的安装与配置[转] CentOS 访问Windows7共享文件夹 svn+ssh方式svn服务器和客户端的配置[转载] 利用Ptrace在Android平台实现应用程序控制[转] AS3地图拼接与战争迷雾的实现[转载] 一些游戏开发相关资料(收集) Bit Twiddling Hacks[转] Unity3D实用工具汇总[转]
Unity中AndroidJavaProxy方法参数为null的坑
hyamw · 2021-11-10 · via 博客园 - hyamw

AndroidJavaProxy是个好东西,可以让安卓原生代码直接调用Unity的代码,而不用通过SendMessage的方式。

今天在使用的过程中发现一个问题,Android调用Unity的方法时报错:

No such proxy method: xxxx(AndroidJavaObject)

经过各种尝试和Google以后发现了最终的原因:

首先贴出代码

Java代码IListener.java

package com.company.test;

public interface IListener {
    public void onComplete(String error);
}

Java代码:Test.java

package com.company.test;

public class Test {
    
    private IListener listener;
    
    public void setListener(IListener listener) {
        this.listener = listener;
    }
    
    public void doTask() {
        listener.onComplete(null);
    }
    
    public static Test create() {
        return new Test();
    }
}

Unity代码:Test.cs

using UnityEngine;

public class Test : MonoBehaviour
{
private AndroidJavaObject nativeJavaObject;

class Listener : AndroidJavaProxy
{
public Listener() : base("com.company.test.IListener")
{

}

void onComplete(string error)
{
Debug.Log($"onComplete:{error}");
}
}
// Start is called before the first frame update
void Start()
{
AndroidJavaClass javaClass = new AndroidJavaClass("com.company.test.Test");
nativeJavaObject = javaClass.CallStatic<AndroidJavaObject>("create");
nativeJavaObject.Call("setListener", new Listener());
nativeJavaObject.Call("doTask");
}
}

  Unity场景中把Test.cs脚本挂到GameObject上打包在真机运行会报以下错误:

No such proxy method: Test+Listener.onComplete(UnityEngine.AndroidJavaObject)

问题出现的是在UnityEngine.AndroidJavaProxy.Invoke的实现中

public virtual AndroidJavaObject Invoke(string methodName, object[] args)
    {
      Exception inner = (Exception) null;
      BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
      System.Type[] types = new System.Type[args.Length];
      for (int index = 0; index < args.Length; ++index)
        // 如果参数为null则将类型设置为AndroidJavaObject
        types[index] = args[index] == null ? typeof (AndroidJavaObject) : args[index].GetType();
      try
      {
        MethodInfo method = this.GetType().GetMethod(methodName, bindingAttr, (Binder) null, types, (ParameterModifier[]) null);
        if (method != null)
          return _AndroidJNIHelper.Box(method.Invoke((object) this, args));
      }
      catch (TargetInvocationException ex)
      {
        inner = ex.InnerException;
      }
      catch (Exception ex)
      {
        inner = ex;
      }
      string[] strArray = new string[args.Length];
      for (int index = 0; index < types.Length; ++index)
        strArray[index] = types[index].ToString();
      if (inner != null)
        throw new TargetInvocationException(this.GetType().ToString() + "." + methodName + "(" + string.Join(",", strArray) + ")", inner);
      AndroidReflection.SetNativeExceptionOnProxy(this.GetRawProxy(), new Exception("No such proxy method: " + (object) this.GetType() + "." + methodName + "(" + string.Join(",", strArray) + ")"), true);
      return (AndroidJavaObject) null;
    }

当Java调用Unity方法传递过来的值为null时,AndroidJavaProxy会按照参数类型为AndroidJavaObject的方式去查找方法(见上面第8行代码),自然就找不到。然后就报错了

解决方法也很简单,重写Invoke方法避免查找Method失败就可以了

public override AndroidJavaObject Invoke(string methodName, object[] args)
        {
            if (methodName == "onComplete")
            {
                onComplete(args[0] as string);
                return null;
            }
            return base.Invoke(methodName, args);
        }

再次打包程序运行就不会报错,能正常输出日志了.

   PS:上面的修复代码只是测试使用,正式项目中请自行补全错误处理,参数转换以及多方法的支持等代码