android - 使用 startService 启动服务时如何获取 IBinder/ServiceConnection/onServiceConnected?

标签 android service

当我使用 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/

相关文章:

android - 连续录制音频并更新 View

java - 如何获取自己App的Top Activity名称

java - Android Gingerbread : Can't create handler inside thread that has not called Looper. 准备()

service - 如何使用 Inno Setup 安装 Windows 服务?

c# - .NET ServiceController.WaitForStatus 忽略超时

android - 如何在 Canvas 上用 x 点旋转位图?

python - 在 C 中进行连接管理有哪些好方法?

android - 从我的 Android 应用打开 Chromecast YouTube 视频

Android可绘制: layer-list repeat bitmap does not load when entirely covered

java - 如何使用 SQL 数据库在 Fragment 上创建 Adapter ListView?