其他分享
首页 > 其他分享> > Unity与Android交互

Unity与Android交互

作者:互联网

Unity调用 Android代码

Unity版本:2019.4.30
1.将unity class.jar文件放入libs文件夹中
在这里插入图片描述

2.UnityPlayerActivity.java在这里插入图片描述

3.UnityPlayerActivity.java里引入两个包

import com.unity3d.player.IUnityPlayerLifecycleEvents;
import com.unity3d.player.UnityPlayer;

4.AndroidManifest.xml 文件加入以下代码

<meta-data
                android:name="unityplayer.UnityActivity"
                android:value="true" />

package包名要与unity包名一致
在这里插入图片描述

5.gradle配置
因为要打包成aar包, 需要做以下修改
在这里插入图片描述

6.MainActivity中编写代码

package com.xingame.unitycallandroid;

import android.os.Bundle;
import android.widget.Toast;

import com.unity3d.player.UnityPlayer;

public class MainActivity extends UnityPlayerActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
    }

    //unity调用Android
    public void UnityCallAndroid () {

        Toast.makeText(this,"unity调用android成功", Toast.LENGTH_LONG).show();

        AndroidCallUnity();
    }
    
    //android调用unity
    public void AndroidCallUnity () {

        //第1个参数为Unity场景中用于接收android消息的对象名称
        //第2个参数为对象上的脚本的一个成员方法名称(脚本名称不限制)
        //第3个参数为unity方法的参数
        UnityPlayer.UnitySendMessage("receiveObj", "UnityMethod", "This is args.");
    }

}

7.buid后将文件复制到unity对应文件中(这里不细说了了)
8.unity添加脚本,调用android(创建unity UI省略)

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SDKTest : MonoBehaviour
{
    private AndroidJavaClass jc;
    private AndroidJavaObject jo;

    private Button btn;
    private static Text text;

    private void Awake()
    {
        btn = transform.Find("Button").GetComponent<Button>();
        text = transform.Find("Text").GetComponent<Text>();
        btn.onClick.AddListener(OnBtnClickHandler);
    }


    private void OnBtnClickHandler()
    {
        using (jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer")){
            using (jo = jc.GetStatic<AndroidJavaObject>("currentActivity")){
                jo.Call("UnityCallAndroid");
            }
        }
    }

    /// <summary>
    ///  被Android中AndroidCallUnity调用
    /// </summary>
    /// <param name="str"></param>
    public void UnityMethod(string str)
    {
        Debug.Log("UnityMethod被调用,参数:" + str);
        text.text = str;
    }
}


Unity的AndroidJavaProxy的使用

android代码:
接口:

package com.xingame.unitycallandroid;

public interface TestInterface {
    void func_1();
}

package com.xingame.unitycallandroid;

public class MainActivity2{

    public static MainActivity2 instance;
    private  int numb = 0;

    private TestInterface mTestInterface;

    public void SetTestInterface(TestInterface testInterface){
        mTestInterface = testInterface;
        mTestInterface.func_1();
    }

    public static MainActivity2 GetInstance(){
        if (instance==null){
            return new MainActivity2();
        }
        return instance;
    }

    public int UnityCallAndroid2 () {
        return numb;
    }
  }

unity代码:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SDKTest : MonoBehaviour
{
    private AndroidJavaClass jc;
    private AndroidJavaObject jo;

    private Button btn;
    private static Text text;

    private static DateTime selectedTime = DateTime.Now;
    public static Text info;

    public class OnDateSetListener : AndroidJavaProxy
    {
        public OnDateSetListener() : base("android.app.DatePickerDialog$OnDateSetListener") { }

        void onDateSet(AndroidJavaObject view, int year, int month, int dayOfMonth)
        {
            text.text = year + "/" + (month + 1) + "/" + dayOfMonth;
        }
    }

    public class TestInterface : AndroidJavaProxy
    {
        public TestInterface() : base("com.xingame.unitycallandroid.TestInterface") { }
        public void func_1()
        {
            info.text = "8888";
        }
    }


    private void Awake()
    {
        btn = transform.Find("Button").GetComponent<Button>();
        text = transform.Find("Text").GetComponent<Text>();
        info = transform.Find("Info").GetComponent<Text>();


        btn.onClick.AddListener(OnBtnClickHandler);
    }

    void Start()
    {
        
        AndroidJavaObject currentActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
        currentActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
        {
            new AndroidJavaObject("android.app.DatePickerDialog", currentActivity, new OnDateSetListener(), selectedTime.Year, selectedTime.Month - 1, selectedTime.Day).Call("show");
        }));
    }

    public void OnBtnClickHandler2()
    {
        //通过对象调用方法
        /*using (jo = new AndroidJavaObject("com.xingame.unitycallandroid.MainActivity2")) {          
                text.text = jo.Call<int>("UnityCallAndroid2").ToString();   
        }*/
        using (jc = new AndroidJavaClass("com.xingame.unitycallandroid.MainActivity2")) {
            jo = jc.CallStatic<AndroidJavaObject>("GetInstance");   //通过类调用静态方法
            jo.Call("SetTestInterface", new TestInterface());
        }
    }
}


unity调用Android 震动

android代码

public void UnityCallVibrate(int time){
    Vibrate(this,time);
}

public static void Vibrate(final Activity activity, long milliseconds) {
    Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
    vib.vibrate(milliseconds);
}

unity代码


#if UNITY_ANDROID&& !UNITY_EDITOR
    AndroidJavaClass jc;
    AndroidJavaObject jo;
#endif

 private void Start()
{
#if UNITY_ANDROID && !UNITY_EDITOR
    jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
    
#endif
}

private void Vibrate(int time)
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        jo.Call("UnityCallVibrate", time);
#endif
    }

unity调用Android Toast

unity代码

public void ToaskMakeTest(string str)
    {
        #if UNITY_ANDROID && !UNITY_EDITOR
        AndroidJavaObject context = jo.Call<AndroidJavaObject>("getApplicationContext");
        AndroidJavaClass toast = new AndroidJavaClass("android.widget.Toast");
        jo.Call("runOnUiThread", new AndroidJavaRunnable(() =>
		{
            toast.CallStatic<AndroidJavaObject>("makeText", context, str, toast.GetStatic<int>("LENGTH_LONG")).Call("show");
        }));
        
        #endif
    }

检测是否连接网络

android代码

public boolean IsHaveNetwork()
{
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo == null || !networkInfo.isAvailable()) {
        //没有联网
        return false;
    } else {
        //有网络
        return true;
    }
}

unity代码


private bool currntNet = false;
#if UNITY_ANDROID && !UNITY_EDITOR
jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
#endif

public bool DetectionNetwork()
{
#if UNITY_ANDROID && !UNITY_EDITOR
    //网络从无到有
    if (currntNet != jo.Call<bool>("IsHaveNetwork") && currntNet == false)
    {
        currntNet = jo.Call<bool>("IsHaveNetwork");

    }
    return currntNet;
#else
	return true; 
#endif
    
}

标签:void,unity,private,Unity,jo,using,Android,交互,public
来源: https://blog.csdn.net/qq_42368728/article/details/120770297