unity3d 獲取電量電池狀態等 android and ios
阿新 • • 發佈:2019-01-26
獲取電量
C#
public static int GetBatteryLevel()
{
int level = 0;
#if UNITY_ANDROID
try
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity" );
AndroidJavaClass unityPluginLoader = new AndroidJavaClass("java類全名");
level = unityPluginLoader.CallStatic<int>("GetBatteryLevel", currentActivity);
}
catch (System.Exception e)
{
}
#elif UNITY_IOS
level = (int)_IOS_GetBatteryLevel();
#endif
return level;
}
java
public static int GetBatteryLevel(Activity currentActivity) {
int level = 0;
try {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intent = currentActivity.registerReceiver(null, ifilter);
level = intent.getIntExtra("level" , 0);// 獲得當前電量
// int scale = intent.getIntExtra("scale", 0);//獲得總電量
// int status = intent.getIntExtra("status", 0);//電池充電狀態
// int health = intent.getIntExtra("health", 0);//電池健康狀況
// int batteryV = intent.getIntExtra("voltage", 0); //電池電壓(mv)
// int temperature = intent.getIntExtra("temperature", 0);
// //電池溫度(數值)
} catch (Exception e) {
}
}
return level;
}
ios
float _IOS_GetBatteryLevel()
{
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float level = [myDevice batteryLevel] * 100;
return level;
}
獲取電池狀態
C#
public static bool GetBatteryChargingState()
{
bool isCharging = false;
#if UNITY_ANDROID
try
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaClass unityPluginLoader = new AndroidJavaClass("java類全名");
isCharging = unityPluginLoader.CallStatic<bool>("GetBatteryChargingState", currentActivity);
}
catch (System.Exception e)
{
}
#elif UNITY_IOS
isCharging = (bool)_IOS_GetBatteryChargingState();
#endif
return isCharging;
}
java
public static boolean GetBatteryChargingState(Activity currentActivity) {
boolean isCharging = false;
try {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intent = currentActivity.registerReceiver(null, ifilter);
int status = intent.getIntExtra("status", 0);// 電池充電狀態
if (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL) {
isCharging = true;
}
} catch (Exception e) {
}
}
return isCharging;
}
IOS
bool _IOS_GetBatteryChargingState()
{
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
bool isCharging = false;
UIDeviceBatteryState state = [myDevice batteryState];
if(state == UIDeviceBatteryStateCharging)
{
isCharging = true;
}
return isCharging;
}