我怎么可以通知从广播接收器正在运行的活动? [英] how can I notify a running activity from a broadcast receiver?
问题描述
我有一个活动,它需要响应于广播事件。 因为一个活动不能是一个广播接收器的同时, 我做了一个广播接收器。
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?
推荐答案
广播的通知。 :)如果你想说,开始一项活动或提供的服务等的基础上接收到的广播,那么你需要一个独立的广播接收器和你把你的清单文件。但是,如果你希望你的活动本身来响应广播,那么你创建你的活动广播接收机的一个实例并注册它。
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.
我使用的模式是:
public class MyActivity extends Activity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(...) {
...
}
});
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_ACTION);
this.registerReceiver(this.receiver, filter);
}
public void onPause() {
super.onPause();
this.unregisterReceiver(this.receiver);
}
}
那么,这样上课的时候被创建(也可以做的onCreate)接收器被实例化。然后在onResume /的onPause我处理注册和注销的接收器。然后在reciever的的onReceive
方法,我做的一切必要措施使活动的反应我想,当它接收广播的方式。
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.
这篇关于我怎么可以通知从广播接收器正在运行的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!