getting battery level at android widget

若如初见. 提交于 2020-01-01 08:56:28

问题


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.


回答1:


hackbod gave the solution at the comments:

" use getApplicationContext().registerReciever() "




回答2:


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.



来源:https://stackoverflow.com/questions/3691579/getting-battery-level-at-android-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!