First write the test script in Unity:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AndroidTest : MonoBehaviour {
public InputField _field;
public Text _text;
/// <summary>
/// Unity调用安卓方法
/// </summary>
public void OnClickBtn1() {
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("U3D_ShowToast1");
}
/// <summary>
/// 给安卓传递参数
/// </summary>
public void OnClickButton2()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("U3D_ShowToast2", _field.text);
}
/// <summary>
/// 接收安卓返回值
/// </summary>
public void OnClickButton3()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
_text.text = jo.Call<string>("U3D_GetValue");
}
/// <summary>
/// 安卓调用Unity方法
/// 这里通过 Unity调安卓 安卓调Unity
/// </summary>
public void OnClickButton4()
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("U3D_ShowToast3", "Canvas", "BecallFunc","123456789");
}
//安卓调Unity的方法
private void BecallFunc(string _contest) {
SetUILabelText(ref _contest);
}
private void SetUILabelText(ref string value)
{
_text.text = value;
}
}
Four button binding methods, set the package name and then export the project:
After exporting it is as follows:
Open Android Studio:
Add script:
public void U3D_ShowToast1(){
Toast.makeText(this,"U3D_ShowToast1",Toast.LENGTH_LONG).show();
}
public void U3D_ShowToast2(String pInput){
Toast.makeText(this,pInput,Toast.LENGTH_LONG).show();
}
//unity调用android的方法返回一个字符串
public String U3D_GetValue(){
return "hmy";
}
//android调用unity的方法
//第一个参数是unity中的物体对象名字
//第二个参数是函数名
//三个参数是传给函数的参数
public void U3D_ShowToast3(String objName,String funname, String info){
UnityPlayer.UnitySendMessage(objName,funname,"Info:"+info);
}
Find Build in the menu—》Build APK. After successful packaging, install the APK to the device for testing.
Test video:
Unity exports it as an installation project and publishes the APK before testing.mp4