-1

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?

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
vulterey
  • 63
  • 6
  • _"For obvious reasons, I cannot put it into the onCreate() method as it has a return statement."_ I don't see why it's obvious or even true. Your `onCreate()` method could call the method, receive the result and then continue with whatever comes next in `onCreate()`. But of course to update the battery level every now and then you'd need to call it again every now and then. Maybe with a `Thread` and a `Runnable`. Maybe with `AlarmManager`. Maybe in some other way... – Markus Kauppinen Jan 30 '19 at 15:04

1 Answers1

0

Thanks for the suggestion. After a few hours of testing, I came up with a different idea. So, if anyone will come up to that same issue, below solution works for me, so it worth to try it. I placed my code in onCreateEngine() and store the result in a variable, then in onDraw() method I only have to use this variable to represent battery level in the way I need it.

@Override
public Engine onCreateEngine() {

    //Battery

    getApplicationContext().registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context battContext, Intent battIntent) {
            batteryLevel = (int) (100 * battIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) / ((float) (battIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1))));
            calcBatteryAngle();
        }
    }, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    //Battery

    return new Engine();
}

So far the above code works for me if anything will change in the next few days I will update this post.

vulterey
  • 63
  • 6