如何从广播接收器通知正在运行的活动?

发布于 2024-09-06 22:29:57 字数 116 浏览 2 评论 0原文

我有一个活动,它需要响应广播事件。 由于一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够运 2024-09-13 22:29:57

广播就是通知。 :) 如果您想说,根据收到的广播启动一项活动或服务等,那么您需要一个独立的广播接收器,并将其放入清单文件中。但是,如果您希望活动本身响应广播,那么您可以在活动中创建广播接收器的实例并在那里注册。

我使用的模式是:

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 中我处理注册和注销接收器。然后,在接收者的 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:

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);
    }
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文