Android端:
package com.myc.sdkbase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
public class MainActivity extends UnityPlayerActivity {
private static MainActivity instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
instance = this;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public int Sum(int x, int y)
{
return x + y;
}
public int Max(int x, int y)
{
return Math.max(x, y);
}
public static MainActivity GetInstance()
{
return instance;
}
public void CallUnityFun(String str)
{
String receiveObj = "Main Camera";
String receiveMethod = "Receive";
UnityPlayer.UnitySendMessage(receiveObj, receiveMethod, str + " Android Call Unity.");
}
}
Unity端:
using UnityEngine;
using UnityEngine.UI;
namespace SDKBase
{
public class MessageHandler : MonoBehaviour
{
private AndroidJavaClass m_jc;
private AndroidJavaObject m_jo;
[SerializeField]
private Text m_text;
[SerializeField]
private Text m_textReceive;
// Start is called before the first frame update
void Start()
{
m_jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
m_jo = m_jc.GetStatic<AndroidJavaObject>("currentActivity");
}
public void OnClickSum()
{
AndroidJavaClass jc = new AndroidJavaClass("com.myc.sdkbase.MainActivity");
AndroidJavaObject jo = jc.CallStatic<AndroidJavaObject>("GetInstance");
m_text.text = jo.Call<int>("Sum", 5, 3).ToString();
}
public void OnClickMax()
{
AndroidJavaClass jc = new AndroidJavaClass("com.myc.sdkbase.MainActivity");
AndroidJavaObject jo = jc.CallStatic<AndroidJavaObject>("GetInstance");
m_text.text = jo.Call<int>("Max", 5, 3).ToString();
}
public void OnClickCall1()
{
m_jo.Call("CallUnityFun", "Test1");
}
public void OnClickCall2()
{
AndroidJavaClass jc = new AndroidJavaClass("com.myc.sdkbase.MainActivity");
AndroidJavaObject jo = jc.CallStatic<AndroidJavaObject>("GetInstance");
jo.Call("CallUnityFun", "Test2");
}
public void Receive(string str)
{
m_textReceive.text = str;
}
}
}
参考链接:https://www.cnblogs.com/msxh/p/7220741.html
后来在看宣雨松博客时看到Unity调用Android部分可以写成:
using (AndroidJavaClass jc = new AndroidJavaClass("com.myc.sdkbase.MainActivity"))
{
using (AndroidJavaObject jo = jc.CallStatic<AndroidJavaObject>("GetInstance"))
{
m_text.text = jo.Call<int>("Sum", 5, 3).ToString();
}
}
了解到using后面接实现了 IDisposable 的对象可以在码块结束后自动Dispose。