unity中获取手机电量

注意:只能在真机中显示,编辑器没法显示

a.Android版
  1.通过C#直接读取,下面的GetBatteryLevel()方法
int GetBatteryLevel()
{
try
{
string CapacityString = System.IO.File.ReadAllText("/sys/class/power_supply/battery/capacity");
return int.Parse(CapacityString);
}
catch (Exception e)
{
Debug.Log("Failed to read battery power; " + e.Message);
}
return -1;
}
}
  b.iOS版
  iOS需要用到xcode编写.a静态链接库
  1.在xcode编写.mm文件,实现C++调用iOS的API得到手机电量,部分代码如下:
  
  float getiOSBatteryLevel()
    {
      [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
      return [[UIDevice currentDevice] batteryLevel];
    }
  
  2.将上面.mm编译好的.a文件放入Unity工程Assets-Plugins-iOS下(路径不能错);在C#中使用下面的方法调用:
[ DllImport( "__Internal" )]
private static extern float getiOSBatteryLevel();

在C#调用此函数就可获得iOS电量

posted on 2017-10-27 13:47  FingerCaster  阅读(1180)  评论(0编辑  收藏  举报

导航