Unity and Android communication: Access Android jar package in Unity

       Recently, some native methods in Android have been used in projects, but Unity itself cannot implement them. As the saying goes, a good memory is worse than a bad writing, so record the test process. It will be convenient for you to use it in the future.

      This test mainly tests an APP developed natively on Android to transmit messages, and an APP developed by Unity to receive messages and perform related processing. Of course, the two APPs are installed on the same Android device. The test only involves Unity receiving the data and printing it out first. The other two are to test the static methods and non-static methods in the jar that are called in Unity.

       First, I asked my Android development colleagues to help me create a jar package. Use the jd-gui.exe tool to view the source code in the jar. Click jd-gui.exe to start this tool directly:

Click File -->Open File to find the jar and open it:

 

 

Import the jar into Unity and place it under Plugin/Android:

At the same time, you must also import an AndroidMainfest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.xx.xxxx" android:versionName="1.0" android:versionCode="1" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="true" android:isGame="true" android:banner="@drawable/app_banner">
    <activity android:name="com.gxxxx.unitymoduletest.MainActivity" android:label="@string/app_name" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
        <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
      </intent-filter>
    </activity>
  </application>
  <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="23" />
  <uses-feature android:glEsVersion="0x00020000" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="25" />
  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>

 

Create test code on Unity:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class test : MonoBehaviour {
    public Text text1;
    public Text text2;
    public Text text;
    public Text text4;
    public string AndroidClassName = "com.gxxx.unitymoduletest.MainActivity";
    public string GetLotMsgJsonMethod = "getLotMsgJson";
    public string GetIssMsgJsonMethod = "getIssMsgJson";
    public string GetHistoryTrendMethod = "getHistoryTrend";
    public string GetTestMethod = "getTestMethod";
    private AndroidJavaClass Ajc;
    public void FetchAndroidData()
    {
        if (Application.platform != RuntimePlatform.Android)
            return;
        //调用静态方法测试
        var LotMsgJson = Ajc.CallStatic<string>(GetLotMsgJsonMethod);
        if (!string.IsNullOrEmpty(LotMsgJson)) {
            text1.text = LotMsgJson;
            Debug.Log(LotMsgJson);
        }


        var IssMsgJson = Ajc.CallStatic<string>(GetIssMsgJsonMethod);
        if (!string.IsNullOrEmpty(IssMsgJson))
        {
            text2.text = IssMsgJson;
            Debug.Log(IssMsgJson);
        }


        var HistoryTrend = Ajc.CallStatic<string>(GetHistoryTrendMethod);
        if (!string.IsNullOrEmpty(HistoryTrend))
        {
            text.text = HistoryTrend;
            Debug.Log(HistoryTrend);
        }
    }

    private void Awake()
    {
        Ajc= new AndroidJavaClass(AndroidClassName);
    }
    private void Start()
    {
        FetchAndroidData();
    }

    //启动另外一个APP  调用非静态方法
    public void OpenOtherApp() {
        text4.text = "1";
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("UpApp");
        text4.text = "2";       
    }
    //调用非静态方法测试
    public void TestButton() {
        StartCoroutine(GetStr());
    }

    IEnumerator GetStr() {
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("setTestMethod");
        yield return new WaitForEndOfFrame();
        var str = pluginClass.CallStatic<string>(GetTestMethod);
        text4.text = str;
    }
    public void QuictApp()
    {      
        Application.Quit();
    }
}

For static method calls: 

 AndroidJavaClass jc= new AndroidJavaClass(AndroidClassName);

 var LotMsgJson = jc.CallStatic<string>(“method name”)

For calls to non-static methods:

       AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");//You must write
        AndroidJavaObject like this jo = jc.GetStatic<AndroidJavaObject>("currentActivity");//You must write
        jo.Call("method name" like this );     

In Unity, the test code is bound to MainCamera, and the button binds the corresponding method:

 

Finally release the Apk to wrap Android devices for testing.

Test Results:

    Start the app developed natively on Android, click to open the Unity development program, and the app developed by Unity will open. At the same time, after entering, the static method in the package will be executed.

Click the test button: text4 displays the hell word in the jar package, indicating that the non-static setTestMethod method in the package is executed, and then the result is returned by calling the static method getTestMethod.

Click to open the APP, and the Android APP program will be opened, and the APP will run in the background.

 

 

Guess you like

Origin blog.csdn.net/hemiaoyuan1989/article/details/105732516