后台活动中的BroadcastReceiver是否有可能接收广播?
是否有可能BroadcastReceiver处于已进入后台接收广播的活动中?如果没有,我该怎么办?
编辑:
让我澄清一下我真正需要什么。 我有一项将从蓝牙接收数据的服务。 当它成功从蓝牙设备获取数据时,服务将广播。
活动分为三种情况。
- 前景
弹出一个对话框并询问用户一些信息 我认为这可以通过在活动
- 后台
中注册接收器来简单地完成,我只是不知道如何执行这部分。 如果我在应用程序中注册接收器,则会显示通知。看了下面的答案后,我想我可以在应用程序中注册。
- 睡觉 唤醒设备。
谢谢。
Is it possible that BroadcastReceiver in an activity which have gone to background receiving broadcast? If not, what should I do?
EDIT:
Let me clarify what I really need.
I have a service that will receive data from bluetooth.
When it get data from blue-tooth device successfully, the service will broadcast.
And there are three cases of the activity.
- foreground
Popup a dialog and ask for user something
I think it can be simply done by register receiver in activity
- background
I just don't know how to do this part.
If I register the receiver in application, notification is shown. After taking a look of the answers below, I think I can register in Application.
- sleep
Wake up the device.
Thank You.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可能甚至不想要那样。活动并不是为了以这种方式使用而设计的。
您应该使用服务来处理它。或者启动一个 Activity(如果它需要 UI)。
在我看来,有两种选择。
请记住,接收器将在主线程上运行,因此您应该向正在运行的服务发出信号或在此处启动服务或活动。也许是执行单个任务的服务。
使用 IntentService 可以轻松实现执行单个任务的服务。它有点像包装在服务中的异步任务。
You probably don't even want that. Activities are not designed to be used that way.
You should use a service to handle it. Or start an Activity if it needs to have an UI.
There two alternatives the way I see it.
Please keep in mind that the receiver will run on the main thread, so you should signal to a running service or start a service or activity here. Perhaps a service that performs a single task.
A service that performs a single task can easily be implemented using IntentService. It is kind of like an async task wrapped in a service.
当您调用 registerReceiver 并在调用 取消注册接收器。如果您在“后台”时收到广播,则可能意味着您没有将注册和取消注册调用绑定到 Activity 生命周期中的适当方法。
It is possible that you will receive notification anytime after when you call registerReceiver and before you call unregisterReceiver. If you are receive broadcasts when you are in the "background" it probably means you didn't tie the register and unregister calls to the appropriate methods in your Activity's lifecycle.
如果您在 Activity 的上下文中注册广播接收器,只要 Activity 处于活动状态,它就会接收广播。
但是,您可以在应用程序上下文中注册接收器,即使活动不活动,它仍然会接收广播。
If you register the broadcast receiver with the activit's context, it will receive broadcasts as long as the activity is alive.
however, you can register the receiver with the applicatino context, and it will still receive broadcasts even if the activity isn't alive.