如何绑定到由另一个应用程序实例启动的服务

时间:2014-04-23 15:04:56

标签: android android-service background-process

即使应用程序被Android杀死,我也需要运行后台Service。这目前工作得很好。

我的问题是,当我重新启动应用程序(后台服务仍在运行)时,我希望我的Activity绑定到服务以访问其某些方法。当我尝试使用ServiceConnection进行绑定时,永远不会调用onServiceConnected

final private ServiceConnection serviceConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder service) {
        Log.d(TAG, "onServiceConnected");  //this is never called
        MyBackgroundService.ServiceBinder binder = (MyBackgroundService.ServiceBinder) service;
        backgroundService = binder.getService();
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d(TAG, "onServiceDisconnected");
        backgroundService = null;
    }

};

private void bindBackgroundService(){
    this.bindService(new Intent(this, MyBackgroundService.class), serviceConnection, Context.BIND_AUTO_CREATE);
}

我这样做是错误的吗?停止Service并重新启动它会更好吗?

1 个答案:

答案 0 :(得分:0)

由于绑定后台服务的类是单例,并且我的警报广播接收器确保后台服务始终在运行实例化此单例,我可以访问此单例并且我尝试绑定到该服务已经绑定了。