In a search to show the battery level on Wear OS, I tried many of the methods, but I am still missing some vital points which keeps me far from solving my problem.
In one of the answers (Get battery level and state in Android), I found the below code:
public static float getBatteryLevel(Context context, Intent intent) {
Intent batteryStatus = context.registerReceiver(null,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int batteryLevel = -1;
int batteryScale = 1;
if (batteryStatus != null) {
batteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, batteryLevel);
batteryScale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, batteryScale);
}
return batteryLevel / (float) batteryScale * 100;}
For obvious reasons, I cannot put it into the onCreate()
method as it has a return statement. Also, I should not put it into the onDraw()
method to not overload it with calculations.
Where exactly I should put this code to make it work?