很多入坑了的小伙伴应该都知道,很多时候做移动端项目都会有显示当前电池电量的需求
对于这个功能,在unity中要做的事并不多,核心方法就一个,自己做一个定时器或者直接使用协程间隔调用该方法就好了
public int GetBattery() { #if UNITY_EDITOR return 50; #elif UNITY_IPHONE return (int)(GetBattery_iOS() * 100); #elif UNITY_ANDROID return tool.CallStatic<int>("GetBattery"); #else return 50; #endif }
对应的,在java代码中,需要在onCreate函数中创建一个监听器
public class ToolActivity extends UnityPlayerActivity{ public static int _power = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //注册电量获取监听器 registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); } //获得电量 public static int GetBattery() { return _power; } //创建电池信息接收器 private BroadcastReceiver batteryReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { int level = intent.getIntExtra("level", 0);//取得电池剩余容量 int scale = intent.getIntExtra("scale", 100);//取得电池总容量 _power = (level * 100) / scale; } }; @Override //界面销毁时,注销监听器 protected void onDestroy() { super.onDestroy(); unregisterReceiver(batteryReceiver); } }
ios设备就简单了,一个函数就搞定
extern "C" { float GetBattery_iOS() { [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; return [[UIDevice currentDevice] batteryLevel]; } }
当然,在unity中不能忘了引用这个函数
[DllImport("__Internal")] static extern float GetBattery_iOS();