9

I wrote a widget for Android and I'm trying to get the battery level. I've tried using

Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

but I get the error: "IntentReceiver components are not allowed to register to receive intents"

Why? the ACTION_BATTERY_CHANGED is a sticky intent and I don't register a receiver (null in the first parameter).

Any workaround?

Thanks.

Ran
  • 4,117
  • 4
  • 44
  • 70

2 Answers2

8

hackbod gave the solution at the comments:

" use getApplicationContext().registerReciever() "

Ran
  • 4,117
  • 4
  • 44
  • 70
3

Ummmm...that feels like a bug. They must be doing the is-a-BroadcastRecevier check too soon. You might want to create a project that demonstrates the problem, then post that to b.android.com.

In terms of a workaround:

Step #1: Create an IntentService

Step #2: In onHandleIntent(), do your actual widget update work, including getting the battery level

Step #3: Have onUpdate() of your AppWidgetProvider just call startService() on your IntentService.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 12
    Or just use getApplicationContext().registerReciever(). – hackbod Sep 11 '10 at 19:38
  • @hackbod: In this case, `getApplicationContext()` would behave differently than the `Context` that `onReceive()` gets passed in? – CommonsWare Sep 11 '10 at 19:44
  • @Ran: sorry, hers is a comment -- unless she rewrites it as an answer, there's no way for you to accept it. – CommonsWare Sep 12 '10 at 11:13
  • @Ran: The "StackOverflow way" would be for you to write that into a new answer, or edit CommonsWare's answer (if you have permission) to include this info. Then you have an answer you can "accept". – Christopher Orr Sep 12 '10 at 18:21