Unity5.6.6 and Android Studio 3.1.3 version Jar package docking records

Due to the hardware of the product, we need to use a button to control the game. This button communicates directly with the all-in-one board of the Android system. After reviewing the data, we found that the button port development of the Android system is different from that of Windows on the PC. , needs to be developed through android studio, so communication and docking can only be carried out through jar packages. In order to communicate with the technical staff who develop the jar package, and to prepare for directly calling the jar package in unity, I also need to understand the docking method between unity and Android. Make a note here for future reference.


Unity project configuration

Although I have read many articles, they first write about how to create Jar packages and then connect with Unity. However, in the actual process, the Unity project may often be started first, and then the Android system will be connected according to specific needs. So my priority here is to record the preparations for Unity.
Since our project uses Unity5.6.6 version, I also use this version for the test project.

  1. Create a test project
    Specifically create a scenario and related test scripts, as shown in the figure below:
    Insert image description here
    Insert image description here
    In this scenario, I will call two test methods through the Jar package.
    The first method demonstrates the communication method used by Unity to call Android.
    The second method demonstrates the communication method of Android calling Unity. What needs attention is the "ObjJar"
    object in the scene . I hung the test script on this object. The name of this object can be freely defined, but when Android calls Unity's method later, it will retrieve the name of this object and the method name inside the script.
    Insert image description here
  2. Define the interface name in advance
    I will determine the interface name used on the Android side in advance.
    JarTest content is as follows:
using System;
using UnityEngine;
using UnityEngine.UI;

public class JarTest : MonoBehaviour {

    public Text MsgAndroid;
    public Text MsgUnity;

    private AndroidJavaClass mJc;
    private AndroidJavaObject mJo;

    private void Start()
    {
    	// 此处为了稳妥起见进行了一下异常处理判断
        try
        {
        	// 固定写法,获取当前安卓系统的上下文。
        	// 获得位于 com.unity3d.player 包下的 UnityPlayer 类
        	// 所谓上下文在我看来就相当于是Android中的当前运行的Scene
            mJc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");

			// 获得 mJc 所代表的类下的 currentActivity 对象
        	// 相当于获取了之前制作的模块中的 MainActivity 类
            mJo = mJc.GetStatic<AndroidJavaObject>("currentActivity");
        }
        catch (Exception e)
        {
            MsgAndroid.text = string.Format("Error: {0}", e.ToString());
        }
    }
    
	/// <summary>
    /// 点击事件,调用 Jar 包中名为 “add” 的方法,并传入两个参数,获取int类型返回值
    /// </summary>
    public void BtnShowAndroidMsg()
    {
        int msg = mJo.Call<int>("add", 10, 19);
        MsgAndroid.text = string.Format("AndroidMsg: {0}", msg);
    }
    
    /// <summary>
    /// 点击事件,调用 Jar 包中名为 “UnityDebug” 的方法,此方法没有返回值
    /// </summary>
    public void BtnShowUnityMsg()
    {
        mJo.Call("UnityDebug");
    }
    
    /// <summary>
    /// 此方法为 Android 端将要调用的 Unity 中的方法
    /// </summary>
    /// <param name="msg"></param>
    public void JarDebug(string msg)
    {
        MsgUnity.text = string.Format("UnityMsg: {0}", msg);
    }
}
  1. Configure Unity
    Finally, by the way, convert the project to the Android platform and configure the package name.
    Insert image description here
    At this point, the configuration on the Unity side is roughly complete.

Jar package generation

  1. Create an Android Studio project.
    Insert image description here
    Note that the package name here can actually be different from the package name of the Unity project.
    Insert image description here
    The minimum API is in sync with what is set in Unity.
    Insert image description here
    Create an empty project.
    Insert image description here
    Insert image description here
    At this point we have successfully created an Android project.

Insert image description here

  1. Create a Module and add Unity's classes.jar.
    Although the project is created, we will not actually use the scenarios that come with this project. We need to re-create a module (Module) and use this module to create a Jar package.

Insert image description here
Insert image description here
Name the module. Note that the package name here is the package name of the subsequent Jar package. Although there are articles on the Internet that the package name here and the Unity project package name need to be set to the same. However, after testing, the package name here can be customized and does not need to be the same as the Unity package name.
Insert image description here
At this point, a new module has been created. At this time, we need to confirm that "library" is displayed in build.gradle in this module.

Insert image description here
Then find the classes.jar file in Unity's installation path and import it into the libs folder in the module.
The directory of classes.jar may be different in different Unity versions. The location in Unity5.6.6 is as follows:
Unity5.6.6\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono\Release\Classes

Insert image description here
Then right-click classes.jar and select "Add As Library".
Insert image description here
Insert image description here
Insert image description here

  1. Create an Activity and write the docking code
    Insert image description here
    . Check the Launcher Activity option to default this Activity to the initial launcher.
    Insert image description here
    After creation, since I don't need to use the Android page, I delete the xml in the layout folder and delete setContentView(R.layout.activity_main) in the onCreate method.
    Insert image description here
    After deletion, it is as shown in the figure:
    Insert image description here
    After that, we start writing code in MainActivity. First, refer to the jar package provided by Unity. At the same time, let MainActivity inherit UnityPlayerActivity.
    Insert image description here
package com.example.testjar;

import android.os.Bundle;

import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class MainActivity extends UnityPlayerActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    // Unity 端调用的接口,返回参数 a+b 的和
    public int add(int a, int b){
        return a + b;
    }

    // Android 端调用 Unity 的接口
    public void UnityDebug(){
    	// 将会在 Unity 场景中搜索 ObjJar 这个对象名称,并且调用其身上脚本中的 JarDebug 方法,
    	// 传入一个 string 类型参数,如果不许要传参,此处就传一个空字符串
        UnityPlayer.UnitySendMessage("ObjJar", "JarDebug", "调用成功呢!");
    }
}
  1. Jar bag

After completing the above work, all you need to do is to modify the AndroidManifest file in the testjar module.

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

    <application>
        <activity android:name="com.example.testjar.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            // 新添加的部分,是固定写法,位置也是固定
            <meta-data android:name="unityplayer.UnityActivity" android:value="true"/>
        </activity>
    </application>

</manifest>

As shown in the figure:
Insert image description here
Add the content in the red box to ensure that this Activity is set as the default startup item. At the same time, note that it is best to use the full name of the activity "package name" + "class name". In this case it's "com.example.testjar.MainActivity".
Then select the testjar folder and click Make Module 'testjar' in the Build option to generate the jar package.
Insert image description here
The location of the jar package generated by different Android Studio versions is different. The current location of 3.1.3 is as follows
Insert image description here


Unity docks with Android

Import the generated Jar package into the following directory in the Unity project, and also import the AndroidManifest file. AndroidManifest.xml is equivalent to a configuration file with higher permissions than Player Settings in Unity. The items set in AndroidManifest will overwrite the same configuration in Player Settings, such as package name, etc. The assets and res folders in the picture both contain corresponding Android reference resources. Since we have no additional references, they are all empty.
Insert image description here
Check whether the references to scripts in Unity are correct. Whether the button has added a listener.
Pack test after no problem!
Insert image description here


Summarize

The biggest issue that needs attention in this test is the package name issue. Most of the online information I consulted said that the package name of the Jar package should be consistent with the Unity project package name. However, after this test, it can be seen that the package name
of Unity is:
Insert image description here
And the package name of the Jar package is:
Insert image description here
In actual operation, there is no There is a problem and can be called successfully. So what you may need to pay attention to is the configuration of the AndroidManifest problem.
Insert image description here
It may be because the name of this activity needs to be set to the corresponding referenced package name so that the Jar package can be called normally. The specific reasons cannot be delved into due to time and other reasons. If I have the opportunity to learn more in the future, I will continue to add more.

Guess you like

Origin blog.csdn.net/EverNess010/article/details/88680887