我可以从不扩展活动的类发送广播吗?
我有一个实现观察者的类。
我有一个方法,当 Obervered 状态发生变化时,该类中会触发该方法,我想在该方法中发送广播。这意味着我的活动可以侦听这些广播消息并对数据执行某些操作。
这就是我到目前为止
public class DoStuff extends BroadcastReceiver implements Observer
{
public void observe(String message)
{
Log.d("TEST", "Inside observe() on DoStuff " + message);
// Here I want to send out a broadcast to MyActivity with message
// in the extras
}
}
无法使用 context.sendBroadcast
的情况,因为我无权访问这里的应用程序上下文,我该如何实现这一点?
提前致谢
I have a class which implements an Observer.
I have a method which is triggered in this class when the Obervered state changes, I want to sent out a broadcast in this method. This means my activity can listen for those broadcast messages and do something with the data.
This is what I have so far
public class DoStuff extends BroadcastReceiver implements Observer
{
public void observe(String message)
{
Log.d("TEST", "Inside observe() on DoStuff " + message);
// Here I want to send out a broadcast to MyActivity with message
// in the extras
}
}
I can't use context.sendBroadcast
, because I don't have access to the application context here, how can I achieve this?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么使用
BroadcastReciever
来实现Observer
接口?我想如果您确实需要访问Context
实例,Service
或Application
是更好的选择。BroadcastRecievers
仅在onRecieve()
方法调用期间处于活动状态,因此从我的角度来看,使用它们实现Observer
接口是没有意义的。Why do you use
BroadcastReciever
to implementObserver
interface? I guess aService
or anApplication
are better candidates in case you really need access to aContext
instance.BroadcastRecievers
are only alive duringonRecieve()
method call, so from my perspective it makes no sense to implementObserver
interface using them.