当我使用 startService(...) 启动我的服务时,我一直在寻找某种方法来获取 ServiceConnection。
我还没有找到方法,所以我一直在搜索并找到了这个:
Does each Activity need to Bind to a Service & What happens when it was created with startService()
在那里,Commonsware 说在 startService 调用之后我是否调用 bindService 并不重要。
所以我想我首先运行 startService(...) 然后直接在做一个 bindService(...) (这样 onServiceConnected 被调用)。但是随后 Service.onCreate 被执行了两次。可能是因为 startService 还没有“完成”......?
问题是:我如何获得对我的服务(IBinder)的引用,即。如果我使用 startService 启动服务,如何让 onServiceConnected 触发?
- - 编辑 - -
我仍然想知道您可能有的任何答案和想法。我做了一个“黑客”来解决这个问题:
我只是做了一个静态引用(在 SRef.java
中我有 public static IBinder myBinder = null)
,在我的 Service.onCreate
中我简单地做
SRef.myBinder = myBinder;
这对我来说似乎不正确,所以任何关于它应该如何工作的其他想法都会受到赞赏。
最佳答案
我使用完全相同的技术(一个 samba 客户端服务),onCreate
从来没有为我调用过两次,我得到了我期望的绑定(bind)器(通过连接回调)。新的 Activity 开始也不会触发 onCreate
,因为之前的 startService
已经执行了服务的启动。
这是我的代码(可能是微不足道的,但也许有帮助):
Activity ( onCreate
):
startService(new Intent(this, SambaService.class));
bindService(new Intent(this, SambaService.class), sambaServiceConnection,
Context.BIND_AUTO_CREATE);
服务:
private ServiceBinder mServiceBinder = new ServiceBinder();
public class ServiceBinder extends Binder {
public SambaService getService() {
return SambaService.this;
}
}
public IBinder onBind(Intent intent) {
return mServiceBinder;
}
关于android - 使用 startService 启动服务时如何获得 IBinder/ServiceConnection/onServiceConnected?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7744841/