即使没有从 Manifest 实例化,也保持小部件 BroadcastReceiver 处于活动状态
我有一个需要侦听 BATTERY_CHANGED 事件的小部件,但是,由于该事件受到保护并且无法从清单中声明,所以我从应用程序构造函数创建一个新的 BroadcastReceiver:
public void onCreate() {
super.onCreate();
if (DEBUG) Log.d(TAG, "onCreate()");
// Register receivers
if (receiver == null) {
receiver = new MYReceiver(this);
}
// Create new intentfilter
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, intentFilter);
}
然后,从接收器调用 AppWidgetProvider 的静态方法,其中实际上使用 RemoteViews 更新小部件。一切都完美无缺,直到 1 小时过去,之后我的接收器消失,小部件不再更新。我正在使用 2.2.1 固件的 Droid 上进行测试 -
我做错了什么?这是更新小部件的正确方法吗(我只需要该事件,所以如果不需要,我不想拥有服务)。我是否应该使用 AlarmManager 来时不时地确保我的接收器仍然在那里?我可以这样做吗?
谢谢。
i have a widget which needs to listen to BATTERY_CHANGED event, however, since this event is protected and cannot be declared from the manifest i create a new BroadcastReceiver from the Application constructor:
public void onCreate() {
super.onCreate();
if (DEBUG) Log.d(TAG, "onCreate()");
// Register receivers
if (receiver == null) {
receiver = new MYReceiver(this);
}
// Create new intentfilter
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, intentFilter);
}
Then, from the Receiver i call a static method of the AppWidgetProvider which actually update the widget using RemoteViews. Everything works flawlessy until 1 hour as passed, after that time my Receiver disappears and the widget does not update anymore. I'm testing this on a Droid with 2.2.1 firmware-
What i'm doing wrong? Is this the correct way to update the widget (i just need that event so i don't want to have a service if its not needed). Should i use an AlarmManager to be sure from time to time that my receiver is still there? I can i do this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道为什么你的接收器在一小时后丢失了,但是使用 AlarmManager 定期检查它是否仍然存在?因此,如果丢失了,您可以重新注册。
I don't have a clue why your receiver got lost after an hour but what about using the AlarmManager to check periodically if it is still there? So you can re-register it if it got lost.