2010-09-11 86 views
9

我为Android编写了一个小部件,并试图获取电池电量。 我使用在android小部件中获取电池电量

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

尝试,但我得到的错误: “IntentReceiver组件不允许注册以接收意图”

为什么? ACTION_BATTERY_CHANGED是一个粘性意图,我没有注册一个接收器(在第一个参数中为null)。

任何解决方法?

谢谢。

+0

Android的错误吗? http://code.google.com/p/android/issues/detail?id=5111 – Ran 2010-09-12 07:35:22

回答

8

hackbod了在注释的解决方案:

“使用getApplicationContext()registerReciever()。”

3

嗯...感觉像一个错误。他们必须尽快检查is-a-BroadcastRecevier。您可能想创建一个演示该问题的项目,然后将其发布到b.android.com

在解决办法方面:

第1步:创建一个IntentService

第2步:在onHandleIntent(),做你的实际窗口更新工作,包括让电池电量

步骤# 3:您的AppWidgetProvideronUpdate()只需在您的IntentService上拨打startService()即可。

+12

或者只是使用getApplicationContext()。registerReciever()。 – hackbod 2010-09-11 19:38:02

+0

@hackbod:在这种情况下,'getApplicationContext()'的行为会不同于'onReceive()'传入的'Context'吗? – CommonsWare 2010-09-11 19:44:33

+0

@hackbod:它的工作!谢谢! – Ran 2010-09-12 08:03:08