Android交互示例
从Unity2018开始,Unity支持使用Java源码文件作为插件在Unity工程中使用。在构建Android时会编译这些源码(该功能依赖于Gradle构建系统)
1. 创建Java文件
Assets->Plugins->Android->UnityTools.java
注意:文件名必须和类名一致
package com.UnityPackage; import java.io.File; import android.os.Environment; import android.os.StatFs; public class UnityTools { public static long GetFreeStorageSpace() { try { File file = Environment.getDataDirectory(); StatFs stat = new StatFs(file.getPath()); return stat .getAvailableBytes(); //VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2 } catch (Exception e) { } return -1; } }
2. 创建C#文件
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; public class UnityAndroidTools { public static long GetFreeStorageSpace() { try { AndroidJavaObject javaObj = new AndroidJavaObject("com.UnityPakcage.UnityTools"); return javaObj.CallStatic<long>("GetFreeStorageSpace"); } catch(Exception e) { Debug.LogError(e); } return -1; } }
Unity和Andorid回调的交互
1. Java类
package com.UnityPackage; import com.arthenica.mobileffmpeg.Config; import com.arthenica.mobileffmpeg.FFmpeg; import com.arthenica.mobileffmpeg.ExecuteCallback; import com.unity3d.player.UnityPlayer; public class UnityTester { public static long AsyncRun(final String command) { long executionId = FFmpeg.executeAsync(command, new ExecuteCallback() { @Override public void apply(final long executionId, final int returnCode) { UnityPlayer.UnitySendMessage("MainCamera", "RunCallback", String.valueOf(returnCode)); } }); return executionId; } }
2. C#类
注意:BindTester脚本一定要挂在一个名叫"MainCamera"的GameObject对象上。
using System; using System.IO; using System.Text; using UnityEngine;public class BindTester : MonoBehaviour { public void RunCallback(string errorCode) { Debug.Log($"异步执行结果:{errorCode}"); } }