Recentemente, alguns métodos nativos do Android têm sido usados em projetos, mas o próprio Unity não consegue implementá-los. Como diz o ditado, uma memória boa é pior que uma escrita ruim, então registre o processo de teste. Será conveniente para você usá-lo no futuro.
Este teste testa principalmente um APP desenvolvido nativamente no Android para transmitir mensagens e um APP desenvolvido pela Unity para receber mensagens e realizar o processamento relacionado. Claro, os dois APPs estão instalados no mesmo dispositivo Android. O teste envolve apenas o Unity recebendo os dados e imprimindo-os primeiro. Os outros dois são para testar os métodos estáticos e não estáticos no jar que são chamados no Unity.
Primeiro, pedi aos meus colegas de desenvolvimento Android que me ajudassem a criar um pacote jar. Use a ferramenta jd-gui.exe para visualizar o código-fonte no jar. Clique em jd-gui.exe para iniciar esta ferramenta diretamente:
Clique em Arquivo -> Abrir arquivo para encontrar o jar e abri-lo:
Importe o jar para o Unity e coloque-o em Plugin/Android:
Ao mesmo tempo, você também deve importar um arquivo AndroidMainfest.xml:
<?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>
Crie o código de teste no 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();
}
}
Para chamadas de métodos estáticos:
AndroidJavaClass jc= new AndroidJavaClass(AndroidClassName);
var LotMsgJson = jc.CallStatic<string>(“nome do método”)
Para chamadas para métodos não estáticos:
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");//Você deve escrever
AndroidJavaObject assim jo = jc.GetStatic<AndroidJavaObject>("currentActivity");//Você deve escrever
jo.Call("method nome" assim);
No Unity, o código de teste está vinculado a MainCamera e o botão vincula o método correspondente:
Por fim, libere o Apk para preparar dispositivos Android para teste.
Resultado dos testes:
Inicie o aplicativo desenvolvido nativamente no Android, clique para abrir o programa de desenvolvimento do Unity, e o aplicativo desenvolvido pelo Unity será aberto. Ao mesmo tempo, após entrar, o método estático do pacote será executado.
Clique no botão de teste: text4 exibe a palavra hell no pacote jar, indicando que o método setTestMethod não estático no pacote é executado e, em seguida, o resultado é retornado chamando o método estático getTestMethod.
Clique para abrir o APP, e o programa Android APP será aberto e o APP será executado em segundo plano.