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 JavaClass
        javaObject = new AndroidJavaObject("com.lg.mylibrary.JTest", this);
    }

  
    // Call the method in the plugin to invoke the callback
    public void CallJavaMethod()
    {
    
    
        javaObject.Call("ShowLog");
    }

    // This method will be invoked from the plugin
    public 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 update
    void Start()
    {
    
    
        JTest t = new JTest();
        t.CallJavaMethod();
        
    }
}

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

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

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

猜你喜欢

转载自blog.csdn.net/thinbug/article/details/141138667