将服务绑定到 BroadcastReceiver [英] Bind Service to BroadcastReceiver
问题描述
我有一些 Service 类,用于注册多个警报.
I have some Service class, which registers multiple alarms.
在我的 BroadcastReceiver 类中,我希望 onReceive() 方法调用 Service 类的某些方法.
In my BroadcastReceiver class, I want the onReceive() method to call some method of the Service class.
但是,我不知道如何将它们绑定在一起.我试图让 BroadcastReceiver 成为一个内部类,但后来我得到了更多的错误并且根本无法触发警报.
However, I don't see how I can bind them together. I tried to make the BroadcastReceiver an inner class, but then I got more errors and couldn't fire the alarm at all.
谢谢
推荐答案
看http://developer.android.com/reference/android/content/BroadcastReceiver.html 生命周期.BroadcastReceiver 仅用于处理消息.这意味着它的寿命很短,蚂蚁也是无国籍的.所以你不能绑定任何东西.
Look at http://developer.android.com/reference/android/content/BroadcastReceiver.html life cycle. BroadcastReceiver is created only for handling a message. It means that it's life is very short, ant it is also stateless. So you cannot bind anything to it.
无论如何你可以尝试启动一个service表单onReceive(Context context, Intent intent)
BroadcastReceiver的方法,像这样:
Anyway you can try to start a service form onReceive(Context context, Intent intent)
method of BroadcastReceiver,
like this:
public void onReceive(Context context, Intent intent) {
Intent intent2 = new Intent(context, GCMService.class);
intent2.putExtras(intent);
context.startService(intent2);
}
然后 a=服务应该处理广播消息.
Then a=the service should handle a broadcast message.
这篇关于将服务绑定到 BroadcastReceiver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!