Unity uses aar to communicate with Android (basic process)

Principle overview : When Unity generates an apk, it will type the aar file with the relative path Plugins/Android into the apk. Through Unity's own API, AndroidJavaClass can call the code in the aar to implement some of the Android native layers. Function

Content of this article : It mainly writes about the basic process of using AAR to communicate with Unity. It does not involve the access to specific SDKs, etc. I am not a native Android developer, so I don’t understand many parts of Android very well, so I can only provide some basic methods, and others We can only rely on everyone to do their own research.

generate aar

To generate aar, the general steps are as follows

  1. In the AndroiStudio editor, create a new empty project (it is only used as a carrier for the aar package. You will see that many things in it are not needed later)
  2. Add new module Android Library
  3. Import the classes.jar package provided by Unity (mainly to pass the compilation, if you don’t use Unity’s code, but Unity calls java, you don’t need to)
  4. Write the function code you need, and adjust AndroiManifest.xml and build.gradle according to the function (mainly configure some references and other contents, which may not necessarily need to be adjusted)
  5. Execute Gradle's assemble task (you can choose the Debug or Release version, but it is the same without adjustment, so you don't need to worry about it when simply accessing it)

The following will introduce the operation of each step in detail

1. Create a new empty project

Insert image description here

When you open AndroidStudio for the first time, you will be asked to create a project. It will provide us with some project templates. If you want to see the cleanest Android project, select No Activity. If you want to do the simplest display or something, just use BasicActivity, the difference between the two is not very big, here I create No Activity

Insert image description here

This interface sets the name of the project and other information. Name and Package name have nothing to do with each other. You can just take them as you like. These parameters will generally not be involved later.

Insert image description here
Insert image description here

On the left side of AndroidStudio, there will be options that allow you to see the structure of the current project. Selecting Project will show the real directory structure of the project on the hard disk, while selecting Android will be streamlined. You only need to pay attention to the files when developing Android. , this has little impact.
Insert image description here
An empty Android project actually has a lot of files, but in reality, it seems to me that there are only two parts. The app is our own code, icons and other content, which we need to pay attention to during the development stage. The other Gradle is When generating apk, you need to pay attention to the release stage. The same is true in the app folder. We don’t need to care too much about everything related to Gradle during the development stage (unless you want to add some dependencies or something)

2. Add new modules

Select File>ProjectStucture in the upper left corner to open the following panel

Insert image description here
As mentioned at the beginning of the article, we created this Android App project just to generate a carrier for aar. We can add a module at this location first (click the + sign)

Insert image description here
The same goes for module name and PackageName. They can be arbitrary, but the Package name here will be used when Unity calls it, because Unity can locate the location of the java function through this package name + class name.

Insert image description here
Select the app module and remove it, because we actually don’t need this thing. It doesn’t matter if we don’t delete it. It’s just that it’s an eyesore here and makes it inconvenient for us to work.

Insert image description here
After removal, the app will actually still be on the disk, but now it can be deleted by right-clicking. Here we can delete it. At the same time, you can see that the Library just created is already there, and the structure inside is similar to that of the app. , nothing special to care about

Insert image description here
The two folders inside can be deleted. They are both for testing and we will not use them. After changing this, you can also go to build.gradle under this path and remove the references to several test tools (these are I don’t know the specific function of this tool. I can only say that deleting it will not affect our subsequent processes). Every time you modify Gradle, Android Studio will prompt you to synchronize it. Here you may encounter a situation where Java cannot connect to the Internet. , at this time it may be that you have configured a VPN before, just use Baidu and delete it.

Insert image description here

3. Import the classes.jar package provided by Unity

The path of this jar package is under the unity installation directory. The relative path is this. I am using the 2019.4.19f1 version. The jar package of this version is 2019.4.19f1\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\il2cpp\Release\Classes
. There is no UnityPlayerActivity java class. This class is under 2019.4.19f1\Editor\Data\PlaybackEngines\AndroidPlayer\Source\com\unity3d\player. You need to import it yourself. We can’t use it here, so we won’t import it.

Insert image description here

Just drag it under libs. At this time, the file is only placed on the disk. The project has not yet referenced the jar package, so you need to right-click classes.jar and select Add As Libraray at the bottom of the list. Normally you You can see the code and other contents in this jar package.

Insert image description here

4. Write code

This step varies from person to person, which means that the basic environment has been set up in the previous process, and the rest is to customize it yourself. Here I only provide the simplest code for testing.

package com.jodebug.myapplication;

import android.app.Fragment;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.unity3d.player.UnityPlayer;

public class TutorialTest extends Fragment {
    
    
    private static final String TAG = "TestLibrary";
    private String gameObjectName;
    private static TutorialTest Instance = null;

    public static TutorialTest GetInstance(String gameObject) {
    
    
        if (Instance == null) {
    
    
            Instance = new TutorialTest();
            Instance.gameObjectName = gameObject;
            UnityPlayer.currentActivity.getFragmentManager().beginTransaction().add(Instance, TAG).commit();
        }
        return Instance;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    private int callCount = 0;

    public void UnityCall() {
    
    
        callCount += 1;
        // Java调用Unity代码,第一个参数是场景中,绑定了脚本的物体名,第二个参数是方法名,第三个参数是值
        UnityPlayer.UnitySendMessage(gameObjectName, "JavaPluginCallback", String.valueOf(callCount));
    }
}

I don’t need to change the AndroidManifest here, so now that the code is written, I can start to package aar. Here I post the content of my AndroidManifest (actually the default one)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jodebug.myapplication">

</manifest>

5. Execute assemble task

Insert image description here
The position is on the right, the position of Gradle, and the Task with the gear label under myapplication inside is the target we want to execute. Let me briefly mention what this is. These are some common instructions for Gradle package scripts. The assemble instruction is understandable. Achievements are package instructions, and assemble_release, etc., with suffixes indicate different versions of the package. Release means the release version. Without the suffix, all versions are generated. After execution, an aar will be generated under a build folder (it will be the default if not set).

Insert image description here

You may sometimes not see Tasks at this location. At this time, it is usually because you have other Gradle tasks that are already executing. In this case, you will be prompted at the top of the interface to explain why the task list is not displayed. Go in at this time. Just uncheck the option "Do not execute other tasks during execution"

Insert image description here
After executing the task, the aar we are going to create will be generated under this path, and the rest is the process in Unity.

Unity use aar

Just build a Unity project and put the aar file in the Plugins/Android directory. However, an
Insert image description here
error will actually be reported when packaging at this time, because we have referenced the classes.jar package in the aar before, but Unity will also reference it when packaging the apk. He, this is repeated reference, so you need to delete the classes.jar package in aar, and directly open the aar file in the form of a compressed package (essentially a compressed package). Note that what you delete is not the classes.jar here, but the one in libs
Insert image description here
. , here is the jar generated by the code we wrote ourselves.
All we have to do after that is some C# code minus the java code

using System;
using UnityEngine;
using UnityEngine.UI;

public class JavaConnector : MonoBehaviour
{
    
    
    private readonly string className = "com.jodebug.myapplication.TutorialTest";
    
    public Text javaCallUi;
    public Text javaCallbackUi;

    private int _callCount = 0;
    public void CallJava()
    {
    
    
        try
        {
    
    
            var pluginObj =
                new AndroidJavaClass(className).CallStatic<AndroidJavaObject>("GetInstance", gameObject.name);
            pluginObj.Call("UnityCall");
            _callCount++;
            javaCallUi.text = "call:" + _callCount.ToString();
        }
        catch (Exception e)
        {
    
    
            Console.WriteLine(e);
            throw;
        }
    }

    public void JavaPluginCallback(string text)
    {
    
    
        javaCallbackUi.text = "back:" + text;
    }
}

Here I hide the process of binding the button click event. This should not be difficult if it is based on Unity. A brief explanation of the code is that every time I click, Unity itself displays a number of calls + 1, because it is called in the java layer. At that time, I asked the java layer to call the Unity layer in turn. If they are interconnected, the javacallback will also update the display. This script needs to be bound to any object in the scene (the name does not matter because the name has been dynamically passed java layer) At this point, the code is written and Unity packages the test

final effect

Insert image description here
Initially, I put two numbers 11 that I wrote randomly. Every time I click, it will show how many times I have clicked and how many times the callback has been triggered.

Guess you like

Origin blog.csdn.net/qq_37421018/article/details/125726386