Unity and Android interactive communication series (3)

  In the previous two articles, we have been able to achieve communication between the Unity side and the Android native side by using Java directly or through the two classes AndroidJavaClass and AndroidJavaObject. This can already solve many problems, but this approach is not modular and elegant enough.

  In actual use, compiling the Android side code into an aar package for Unity side to call is more conducive to code management, personnel division of labor, and reducing the coupling between development tools. Moreover, there are currently a large number of third-party libraries provided in the form of aar packages. This document In this section, we mainly demonstrate the process and method of generating an aar package through Android Studio and calling the functions in the aar package in Unity.
The process of generating an aar package in Android Studio is as follows:

  (1) Create a new Android Studio project. In Android Studio, select File → New → New Project, as shown in Figure 1.
Insert image description here

Figure 1 Create a new project

  After selecting New Project, the new project creation panel will open, as shown in Figure 2. Select Phone and Tablet in the list on the left side of the panel, and then select one of the No Activity, Basic Activity, and Empty Activity templates in the image list on the right side. This section Select the Empty Activity template.
Insert image description here

Figure 2 New project creation panel

  After selecting the project template used, click Next to enter the project information filling panel, as shown in Figure 3, where Package name is the package name used and needs to be filled in carefully; Minimum SDK recommends selecting Android 8.0 or above (ARCore does not support Android 7.0 or below); the remaining items can be filled in as needed, and click the Finish button to complete the project creation.

Insert image description here

Figure 3 Fill in project information

  After the project is created, because we want to export the aar package in the form of a module, we first create the application module. Right-click the app directory on the Project list panel on the left side of the newly created project, and select New →Module in the pop-up cascading menu, as shown in Figure 4.

Insert image description here

Figure 4 New Module module

  In the new module panel that opens, because we want to create an Android class library, select Android Library in the list on the left, and then fill in the Module name and other information in the panel on the right, as shown in Figure 5. Finally Click the Finish button to complete the creation of the android2unity module [ In this example, the project name and the module name have the same name. In actual use, it is recommended to name according to the module function and avoid having the same name as the project ].

Insert image description here

Figure 5 Module module information filling panel

  Android Studio will automatically generate the hierarchical structure of the module. Select the java → com.davidwang.android2unity package name under the android2unity module, and right-click on it to open the cascading menu, as shown in Figure 6.

Insert image description here

Figure 6 Create a new Java class under the module

  In the pop-up cascading menu, select New → Java Class to create a new class. The class name in this section is example, and write the code as follows:

//代码片段1
//Java端代码
package com.davidwang.android2unity;

import android.app.Activity;
import android.widget.Toast;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class example {
    
    
    private Activity _unityActivity;
    private String _unityObject;
private String _unityMethod;
//初始化,注册Unity对象与回调方法
    public void Init(String unityObject,String unityMethod){
    
    
        try {
    
    
            Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
            Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype);
            _unityActivity = activity;
        }
        catch (ClassNotFoundException e) {
    
     }
        catch (IllegalAccessException e) {
    
     }
        catch (NoSuchFieldException e) {
    
     }
        _unityObject = unityObject;
        _unityMethod = unityMethod;
}
//通过UnitySendMessage方法传播消息
    private boolean callUnity(String args){
    
    
        try {
    
    
            Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
            Method method =classtype.getMethod("UnitySendMessage", String.class,String.class,String.class);
            method.invoke(classtype,_unityObject,_unityMethod,args);
            return true;
        }
        catch (ClassNotFoundException e) {
    
    }
        catch (NoSuchMethodException e) {
    
    }
        catch (IllegalAccessException e) {
    
    }
        catch (InvocationTargetException e) {
    
    }
        return false;
}
//调用Android端本地方法
    public boolean showToast(String content){
    
    
        Toast.makeText(_unityActivity,content,Toast.LENGTH_SHORT).show();
        callUnity("Call from android");
        return true;
    }
}

  In the above code, we use the UnitySendMessage() message propagation method to call back the Unity side method. Since the UnitySendMessage() method requires clear game objects in the scene and the method names in the game object scripts as parameters, in order to facilitate the call in Unity, here through Init () method injects these two parameters from the Unity side, so there is no need to bind the game object and script method name one by one. At the same time, in order to avoid introducing the Classes.jar package of the Unity engine, reflection is used to obtain the current Activity.

  At this point, the module on the Android side has been completed. Select the android2unity module in the Project list on the left, and then select Build → Rebuild Project in the Android Studio menu to start building the module aar package, as shown in Figure 7. After the build is completed, you can open the android2unity module Find the generated aar package in the build →outputs →aar directory.

Insert image description here

Figure 7 Building module aar package

  Copy the aar package file to the Unity project Assets/Plugins/Android directory or its subdirectory to complete the import of the aar package. In order to test its function, create a new Android2Unity.cs script file in Unity with the following code:

//代码片段2
//C#端代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Android2Unity : MonoBehaviour
{
    
    
    void Start()
    {
    
    
        using(AndroidJavaObject jo = new AndroidJavaObject("com.davidwang.android2unity.example"))
        {
    
    
            jo.Call("Init",gameObject.name, "AndroidCallback");
            bool success = jo.Call<bool>("showToast", "Content from unity");
            if (true == success)
            {
    
    
                Debug.Log("Method executed");
            }
        }
}
//Android端回调的方法
    public void AndroidCallback(string str)
    {
    
    
        Debug.Log(str);
    }
}

  The script logic is relatively simple. First, it instantiates the class on the Android side and injects the callback game object name and script method name through its Init() method. Mount the script file to any object in the scene, connect to the mobile phone, package and run. You can see that the method parameters on the Unity side can be correctly passed to the Android side, and the Android side can also call back the script method on the Unity side correctly.

  Since the UnitySendMessage() method needs to traverse the game objects in the scene, it is not very efficient. Especially if it is called frequently or the scene is complex, it may cause performance problems. In actual development, it is recommended to interact through the AndroidJavaProxy class. By building the module aar package, it is conducive to code management, and can easily integrate third-party class libraries, provide an overall module solution, and simplify the calling form on the Unity side.

  It is much more comfortable to call through this package/library method.

Guess you like

Origin blog.csdn.net/yolon3000/article/details/135231443