我创建了一个自定义视图,可以放在应用程序的不同位置。我无法避免在视图中使用BroadcastReceiver从应用程序的其余部分获取消息。
我读过它不推荐(Where should I unregisterReceiver in my own view?),但是如果我选择使用它,是否有一个从BroadcastManager取消注册视图的地方?
答案 0 :(得分:5)
我建议你使用LocalBroadcastManager。它就像一个BroadcastReceiver,其Intent只能在你的应用程序中看到。
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your code here
}
};
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onPause();
}
@Override
protected void onResume() {
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
IntentFilter filter = new IntentFilter();
filter.addAction(MyClass.MY_ACTION);
lbm.registerReceiver(receiver, filter);
super.onResume();
}
答案 1 :(得分:0)
如@vggonz所说,视图没有像活动那样清晰的生命周期,但是,如果您在onAttachedToWindow()
中注册广播接收器并取消注册onDetachedFromWindow()
,则它会按预期工作。
public class MyView extends View {
private BroadcastReceiver receiver;
public MyView(Context context) {
super(context);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
filter.addAction("SOME_OTHER_ACTION");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
}
};
getContext().registerReceiver(receiver, filter);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (receiver != null) {
getContext().unregisterReceiver(receiver);
receiver = null;
}
}
}