Search code examples
androidservicewidgetbattery

Android battery widget initialized


I have created a battery widget that uses a Service to listen for Battery changes. However because of this, when created the widget must wait before the battery state changes before it can display data.

My question is whether or not there is simple method of interrogating the battery as a one off occurrence.

I may be barking up the wrong tree but I have tried using a BroadcastReceiver in the AppWidgetProvider class to get the initial state of the battery but can't figure out how to stop that so that the service can take it from there.

Any thoughts?

Cheers


Solution

  • I have created a battery widget that uses a Service to listen for Battery changes.

    Note that keeping a service around all of the time is not generally a good idea. Users don't like it and will kill it off with a task killer or the Manage Services screen in Settings. Android doesn't like it either and will eventually stop it.

    Since the battery level does not change very frequently, consider switching to a model where you use AlarmManager and check the battery level every few minutes.

    However because of this, when created the widget must wait before the battery state changes before it can display data.

    No. When you register for ACTION_BATTERY_CHANGED, your BroadcastReceiver is immediately invoked with the last-sent broadcast for that action, since ACTION_BATTERY_CHANGED is a sticky broadcast.

    You can see that in this sample project. The battery information is displayed in the activity immediately -- that is only possible because the onReceive() method is invoked immediately.

    My question is whether or not there is simple method of interrogating the battery as a one off occurrence.

    That too is possible. Call registerReceiver() for ACTION_BATTERY_CHANGED, but with a null BroadcastReceiver. You will be returned the last-sent broadcast Intent for that action. This would be the way to handle it from the AlarmManager event, for example.