如何从广播接收器通知正在运行的活动?
我有一个活动,它需要响应广播事件。 由于一个Activity不能同时作为广播接收者, 我做了一个广播接收器。
我的问题是:如何从广播接收器通知活动? 我相信这是一种常见的情况,那么有没有一种设计模式呢?
I have an activity, it needs to response to a broadcast event.
Since an activity can not be a broadcast receiver at the same time,
I made a broadcast receiver.
My question is: how can I notify the activity from the broadcast receiver?
I believe this is a common situation, so is there a design pattern for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
广播就是通知。 :) 如果您想说,根据收到的广播启动一项活动或服务等,那么您需要一个独立的广播接收器,并将其放入清单文件中。但是,如果您希望活动本身响应广播,那么您可以在活动中创建广播接收器的实例并在那里注册。
我使用的模式是:
因此,这样在创建类时就会实例化接收器(也可以在 onCreate 中执行)。然后在 onResume/onPause 中我处理注册和注销接收器。然后,在接收者的 onReceive 方法中,我会做任何必要的事情,以使活动在收到广播时按照我想要的方式做出反应。
The broadcast is the notification. :) If you want to say, start an activity or a service, etc., based on a received broadcast then you need a standalone broadcast receiver and you put that in your manifest file. However, if you want your activity itself to respond to broadcasts then you create an instance of a broadcast receiver in your activity and register it there.
The pattern I use is:
So, this way the receiver is instantiated when the class is created (could also do in onCreate). Then in the onResume/onPause I handle registering and unregistering the receiver. Then in the reciever's
onReceive
method I do whatever is necessary to make the activity react the way I want to when it receives the broadcast.