在bindService之前等待startService
据我了解,如果我希望一个服务运行,即使没有任何绑定,那么它必须首先使用 startService(Intent i) 启动。
我的问题是,如果我想在启动服务后立即绑定到该服务,以下代码是否能保证使用 startService() 创建该服务?
服务类中的静态方法:
public static void actStart(Context ctx) {
Intent i = new Intent(ctx, BGService.class);
i.setAction(ACTION_START);
ctx.startService(i);
}
绑定活动:
BGService.actionStart(getApplicationContext());
bindService(new Intent(this, BGService.class), serviceConnection, Context.BIND_AUTO_CREATE);
It is my understanding that if I want a service to run even if nothing is bounded to it, then it must first be started with startService(Intent i).
My question is WHAT IF I want to bind to the service immediately after I start it, would the following code guarantee the service is created with startService()?
Static method within the service class:
public static void actStart(Context ctx) {
Intent i = new Intent(ctx, BGService.class);
i.setAction(ACTION_START);
ctx.startService(i);
}
The binding activity:
BGService.actionStart(getApplicationContext());
bindService(new Intent(this, BGService.class), serviceConnection, Context.BIND_AUTO_CREATE);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定您想在这里做什么,但是“Context.BIND_AUTO_CREATE”会创建服务,然后绑定到该服务,即使它尚未启动。
现在如果你想在绑定后立即访问它,你可以使用serviceConnection的onServiceConnected()方法:
I am not sure what you are trying to do here, but "Context.BIND_AUTO_CREATE" creates the service then binds to the service even if it hasn't been started.
Now if you want to access it immediately after binding, you can use the onServiceConnected() method of the serviceConnection:
要添加到 Bugdayci 的答案中,完整的示例如下:
...
如果末尾没有 bindService,则 onServiceConnected() 代码将不会执行。
To add to Bugdayci's answer, a complete example is as follows:
...
Without the bindService at the end, the onServiceConnected() code will not execute.