Notifications
Article
Unity 获取手机设备电量
Published 18 days ago
5
0
设备的电池状态
Android 设备的电池状态:
无需手写JNI,无需引入Plugin,通过安卓BatteryManager获取手机电量、是否在充电的信息。网上的方法大多有错或者不满意的地方。比如 System.IO.File.ReadAllText(“/sys/class/power_supply/battery/capacity”); 就对华为手机无效。

实际使用中要注意:访问电量不要太频繁。

而且该例子的方法可以用来举一反三,相关字段参考 https://developer.android.com/reference/android/os/BatteryManager.html

try
{
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
if(unityPlayer != null)
{
using (AndroidJavaObject currActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
{
if (currActivity != null)
{
using (AndroidJavaObject intentFilter = new AndroidJavaObject("android.content.IntentFilter",
new object[] { "android.intent.action.BATTERY_CHANGED" }))
{
if(intentFilter != null)
{
using (AndroidJavaObject batteryIntent = currActivity.Call<AndroidJavaObject>("registerReceiver", new object[] { null, intentFilter }))
{
/** 是否在充电 **/
int state = batteryIntent.Call<int>("getIntExtra", new object[] { "status", -1 });
if (state == 2/*BATTERY_STATUS_CHARGING*/ || state == 5/*BATTERY_STATUS_FULL*/)
{
// 充电
}
else
{
// 没充电
}
/** 当前电量 **/
int level = batteryIntent.Call<int>("getIntExtra", new object[] { "level", -1 });
int maxLevel = batteryIntent.Call<int>("getIntExtra", new object[] { "scale", -1 });
if (level == -1 || maxLevel == -1)
{
// 以防万一,处理一下,可返回 0.5f
}
else
{
// 电量 = ((float)level / (float)maxLevel);
}
}
}
}
}
}
}
}
}
catch (System.Exception ex)
{
throw;
}




iOS获取电量:

用UIDevice这个原生类。比如获取电量
float System_GetBatteryLevel()
{
  [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
  return [[UIDevice currentDevice] batteryLevel];
}


然后unity里声明后直接调用即可
[DllImport("__Internal")]
private static extern float System_GetBatteryLevel();

Tags:
jeff
高级开发工程师 - Programmer
1
Comments