欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > Unity 编写自己的aar库,并通过AndroidJavaProxy调用访问和返回

Unity 编写自己的aar库,并通过AndroidJavaProxy调用访问和返回

2024/10/24 13:18:58 来源:https://blog.csdn.net/thinbug/article/details/141138667  浏览:    关键词:Unity 编写自己的aar库,并通过AndroidJavaProxy调用访问和返回

安卓部分

我们首先创建一个空项目,我们不需要Activity,所以可以选择NoActivity。
在这里插入图片描述
输入一个包名,我们用不到这个主app包名。
在这里插入图片描述
项目创建好后,再创建新Module
在这里插入图片描述
左边我们选择AndroidLibrary,然后输入包名,这个包名在Unity中需要输入。

在这里插入图片描述

然后我们编写两个脚本,一个是Interface,一个是类。
这里要注意,在Unity中我们通过AndroidJavaProxy调用的只能是interface。
在这里插入图片描述
两个脚本如下:

package com.lg.mylibrary;import android.util.Log;public interface JTestInterface {void ShowBack(String backmsg);}
package com.lg.mylibrary;import android.util.Log;public class JTest  {public JTestInterface mInterface;public JTest(JTestInterface callback){mInterface = callback;}public void ShowLog() {mInterface.ShowBack("back , 哈哈");}
}

然后我们直接Build
在这里插入图片描述
生成的arr会在
E:\AndroidProjects\AndroidJFrameWork\mylibrary\build\outputs\aar\mylibrary-debug.aar
这个路径下,我们复制到Unity的Plugins\Android目录下,没有目录自己手动创建。
在这里插入图片描述

Unity部分

我们在Unity创建一个AndroidJavaProxy类,用来访问。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class JTest : AndroidJavaProxy
{AndroidJavaObject javaObject;public JTest() : base("com.lg.mylibrary.JTestInterface"){// We create an instance of the JavaClass in the constructor// and pass the reference of this class to the JavaClassjavaObject = new AndroidJavaObject("com.lg.mylibrary.JTest", this);}// Call the method in the plugin to invoke the callbackpublic void CallJavaMethod(){javaObject.Call("ShowLog");}// This method will be invoked from the pluginpublic void ShowBack(string xx){Debug.Log("Unity ShowBack 显示LOG :"+xx);// Pass the result to the C# event that we register to in the UI class}}

再来一个脚本实例化这个对象。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class TestShow : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){JTest t = new JTest();t.CallJavaMethod();}
}

我们创建对象放入这个TestShow脚本。然后打包apk,安装。运行结果如下:
在这里插入图片描述

Unity通过访问javaObject.Call(“ShowLog”);访问到了安卓的Lib函数,并进行了返回。

到这里就结束了。
顶部有Android和Unity测试工程下载

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com