我有一个服务,它在第一次被调用时启动并正确绑定(bind),但是当被其他 Activity 调用时,对同一服务的连续绑定(bind)失败。
编码:
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
方法永远不会被调用。我使用一个连接类来进行绑定(bind),所以这两个 Activity 的方法是相同的。该服务还正确添加了 list 文件。有任何想法吗?
非常感谢
最佳答案
在我的情况下,问题与 bindService()
有关.
我在 onResume()
中只调用过一次- 跟随一些样本。
看来bindService()
每次启动服务时都应该调用(在我的例子中是 ContextCompat.startForegroundService()
)。
关于Android服务正确启动/绑定(bind),但只是第一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3380923/