Hi. Please help me. How to read battery status on android ?
up
Source: How to get current battery life on mobile device - Questions & Answers - Unity Discussions
UIDevice device = UIDevice.CurrentDevice();
device.batteryMonitoringEnabled = true; // need to enable this first
Debug.Log("Battery state: " + device.batteryState);
Debug.Log("Battery level: " + device.batteryLevel);
Search before asking. This prevents duplicate threads.
1 Like
Read before you answer, I need to android
Did you test it before replying?
How can he test iOS stuff on android?
I meant did he test the code on android?
public static float GetBatteryLevel()
{
#if UNITY_IOS
UIDevice device = UIDevice.CurrentDevice();
device.batteryMonitoringEnabled = true; // need to enable this first
Debug.Log("Battery state: " + device.batteryState);
Debug.Log("Battery level: " + device.batteryLevel);
return device.batteryLevel*100;
#elif UNITY_ANDROID
if (Application.platform == RuntimePlatform.Android)
{
try
{
using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
if (null != unityPlayer)
{
using (AndroidJavaObject currActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
{
if (null != currActivity)
{
using (AndroidJavaObject intentFilter = new AndroidJavaObject("android.content.IntentFilter", new object[]{ "android.intent.action.BATTERY_CHANGED" }))
{
using (AndroidJavaObject batteryIntent = currActivity.Call<AndroidJavaObject>("registerReceiver", new object[]{null,intentFilter}))
{
int level = batteryIntent.Call<int>("getIntExtra", new object[]{"level",-1});
int scale = batteryIntent.Call<int>("getIntExtra", new object[]{"scale",-1});
// Error checking that probably isn't needed but I added just in case.
if (level == -1 || scale == -1)
{
return 50f;
}
return ((float)level / (float)scale) * 100.0f;
}
}
}
}
}
}
} catch (System.Exception ex)
{
}
}
return 100;
#endif
}
3 Likes
I take you were trolling?
Obviously those libs aren’t even there…
Alright, 5 years later we finally got a concrete solution.
Since Unity 2018.1, you can now get battery level by calling SystemInfo.batteryLevel
2 Likes
This is the function I used to get the complete status of the Battery:
public void UpdateBatteryStatus()
{
if(SystemInfo.batteryStatus == BatteryStatus.Charging)
{
//Do Something
}
else if(SystemInfo.batteryStatus == BatteryStatus.Full || SystemInfo.batteryLevel >= 0.9f)
{
//Do Something
}
else if (SystemInfo.batteryLevel >= 0.61f && SystemInfo.batteryLevel < 0.9f)
{
//Do Something
}
else if (SystemInfo.batteryLevel >= 0.51f && SystemInfo.batteryLevel < 0.61f)
{
//Do Something
}
else if (SystemInfo.batteryLevel >= 0.31f && SystemInfo.batteryLevel < 0.51f)
{
//Do Something
}
else if (SystemInfo.batteryLevel >= 0.11f && SystemInfo.batteryLevel < 0.31f)
{
//Do Something
}
else if (SystemInfo.batteryLevel < 0.11f)
{
//Do Something
}
}