I'm just starting with android development and have written an application to show details about the battery status. Now I wanted to put the whole thing into an widget - and here's the question: Do I really need a update service in the background to listen for ACTION_BATTERY_CHANGED intents? My first thought was to put just a line into the intet-filter tag of the widget in the AndroidManifest.xml - but obviously it's not that simple. If the UpdateService is the right way I'll do so - but I just wanted to make sure what the proper solution is
3 Answers
Do I really need a update service in the background to listen for ACTION_BATTERY_CHANGED intents?
You cannot use a manifest-registered BroadcastReceiver
for ACTION_BATTERY_CHANGED
. It can only be registered by an activity or service via registerReceiver()
.
If you do not have a service in memory for other reasons, a better approach is to poll. Set up an AlarmManager
to check the battery level every so often (configurable, please!). To check the battery level, call registerReceiver()
for an ACTION_BATTERY_CHANGED
IntentFilter
without a BroadcastReceiver
(null
for the first parameter). This will return the last-broadcast ACTION_BATTERY_CHANGED
Intent
, from which you can get the most-recent charge level.

- 986,068
- 189
- 2,389
- 2,491
I suggest you poll the battery status periodically, e.g. every 30 min. To do that you can simply specify a value for updatePeriodMillis
in your AppWidgetProviderInfo
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:updatePeriodMillis="1800000" />
..and update your widget by overriding the onUpdate
method of your AppWidgetProvider
.
edit: As pointed out by Martin, 30 min is actually the shortest interval in which you can receive updates this way.

- 74,165
- 16
- 97
- 99
-
thanks for that - but that would be limited to at least 30 minutes since this is the minimum value for updatePeriodMillis, won't it? – DonGru Aug 10 '10 at 10:01
-
You are right! That's very interesting, because this limitation has not always been there (http://android.git.kernel.org/?p=platform/frameworks/base.git;a=commit;h=851da848e97d9a1ec23a89ff0e200c301f32d690) – Josef Pfleger Aug 10 '10 at 15:01
-
I recon it was introduced because programmers used it to make frequent updates (like every second for clock-widgets) - which probably isn't a good thing for battery-life – DonGru Aug 11 '10 at 08:01
Believe it or not, the following works:
cont.getApplicationContext().registerReceiver(rec, filter);

- 429
- 4
- 13