【问题标题】:Android Service starts/binds correctly, but only the first timeAndroid服务正确启动/绑定,但只是第一次
【发布时间】:2025-12-03 22:35:01
【问题描述】:

我有一个服务在第一次调用时会正确启动和绑定,但在被其他活动调用时,对同一服务的连续绑定会失败。

代码:

activity.startService(new Intent().setClass(activity, ServerListenerService.class));        

xmppServiceConnection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            ServerActivityConnection.this.xmppService = null;
        }

        public void onServiceConnected(ComponentName name, IBinder binder) {
            //set everything up
        }
    };

activity.bindService(new Intent().setClass(activity, ServerListenerService.class), xmppServiceConnection, Activity.BIND_AUTO_CREATE);

第二次,在调用activity.bindService 之后,服务连接的onServiceConnected 方法永远不会被调用。我使用一个连接类来进行绑定,所以这两个活动的方法是相同的。该服务也正确添加了清单文件。

有什么想法吗?

非常感谢

【问题讨论】:

  • 如果您找到了解决方案,请在此处分享,因为我也面临同样的问题

标签: android android-service


【解决方案1】:

在我的情况下,问题与bindService() 有关。 我在onResume() 中只调用过一次 - 遵循一些示例。

似乎每次启动服务时都应该调用bindService()(在我的例子中是ContextCompat.startForegroundService())。

【讨论】: