- Home /
Display battery percentage in Android
Hey devs! I would like to display the android phone's current battery percentage in my game. How would I do that? I looked up several other topics but none of their solutions seem to be working for me.
Someone posted this script for this purpose.
public float GetBatteryLevel() {
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;
but when I attach this to my "public Text bat_lvl;" as "bat_lvl.text = GetBatteryLevel();" I get this error: Cannot implicitly convert type float' to
string'. I know what this error is and why it's here but how do I display a float value to a UI Text is what I'm struggling at.
Any help would be greatly appreciated!
Answer by Ultronium · Mar 20, 2018 at 02:46 PM
Solved it using
int GetBatteryLevel()
{
try {
string CapacityString = System.IO.File.ReadAllText ("/sys/class/power_supply/battery/capacity");
return int.Parse (CapacityString);
} catch (System.Exception e) {
Debug.Log ("Failed to read battery power; " + e.Message);
}
return -1; //if no value is found
}
Answer by Kuuo · Apr 23, 2019 at 03:28 AM
try SystemInfo.batteryLevel
https://docs.unity3d.com/ScriptReference/SystemInfo-batteryLevel.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612154910im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Touch not changing variables, Keypress does 0 Answers
Application.LoadLevel Strange Problem 2 Answers