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
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
AlarmManagerand check the battery level every few minutes.No. When you register for
ACTION_BATTERY_CHANGED, yourBroadcastReceiveris immediately invoked with the last-sent broadcast for that action, sinceACTION_BATTERY_CHANGEDis 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.That too is possible. Call
registerReceiver()forACTION_BATTERY_CHANGED, but with anullBroadcastReceiver. You will be returned the last-sent broadcastIntentfor that action. This would be the way to handle it from theAlarmManagerevent, for example.