Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting battery level at android widget

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.

like image 578
Ran Avatar asked Sep 11 '10 15:09

Ran


2 Answers

hackbod gave the solution at the comments:

" use getApplicationContext().registerReciever() "

like image 166
Ran Avatar answered Nov 15 '22 21:11

Ran


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.

like image 20
CommonsWare Avatar answered Nov 15 '22 20:11

CommonsWare