Java – Android Wear Watch Face gets the percentage of the phone’s battery

Android Wear Watch Face gets the percentage of the phone’s battery… here is a solution to the problem.

Android Wear Watch Face gets the percentage of the phone’s battery

I’m working on an Android Wear watch face and I want to show the battery percentage of my watch and phone. I managed to get a percentage of Watch, but I’m new to Java and Android, so please relax my explanation.

private String getBatteryInfoPhone()
{
    float retVal = 0;

IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus =  registerReceiver(null, iFilter);

int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

retVal = level / (float)scale;

return Integer.toString(Math.round(retVal)) + "%";
}

This is the code I currently have to give me the percentage of my phone.
Note that this is a watch face, so it is a service without an activity.

With this solution, I keep getting 1% instead of the actual percentage.

Solution

batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

You will be given a value between 1 and 100, so you can insert it directly as a percentage. You don’t need to divide it proportionally.

Related Problems and Solutions