当我使用 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
从来没有为我调用两次,并且我得到了 Binder (通过连接回调),正如我所期望的那样。新的 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/