6

我创建了一个自定义视图,可以放置在应用程序的不同位置。我无法避免在视图中使用 BroadcastReceiver 从应用程序的其余部分获取消息。

我读过它不推荐(在我自己的视图中我应该在哪里取消注册接收器?),但如果我选择使用它,是否有地方从广播管理器中取消注册视图?

4

2 回答 2

5

我建议您使用 LocalBroadcastManager。它就像一个广播接收器,其意图只能在您的应用程序内部看到。

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();
}
于 2013-04-09T14:05:10.127 回答
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;
        }
    }
}
于 2020-11-15T15:22:47.490 回答