gpt4 book ai didi

android - 究竟什么时候会调用有界服务的 onServiceConnected?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:17:45 74 4
gpt4 key购买 nike

我正在尝试像这样从另一个服务绑定(bind)服务:

public class ServiceA extends Service {
private ServiceB mDataService;
private boolean mIsBound;

@Override
public void onCreate(){
super.onCreate();
doBindService();
/* ... */
}

@Override
public void onStart(final Intent intent, final int startId){
/*...*/
}

private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mDataService = ((ServiceB.LocalBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mDataService = null;
}
};

void doBindService() {
bindService(new Intent(ServiceA.this, ServiceB.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}

void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
}

这是我从 goolge 的示例中提取的一个简单 fragment :)代码工作正常,mDataService 持有对 ServiceB 实例的引用,但有一件事我无法理解:onServiceConnected 回调是在调用 onStart 之后调用的。正如我在 android 文档中看到的那样,the callback is running on the main thread - 但我能指望它总是按我的顺序发生吗? onCreate -> onStart -> onServiceConnected ?

最佳答案

如果官方开发指南(仍然)不清楚,Context.bindService() 确实是一个异步调用。这也解释了为什么将 ServiceConnection.onServiceConnected() 作为回调实现。

查看 dev guide :

A client binds to a service by calling bindService(). When it does, it must provide an implementation of ServiceConnection, which monitors the connection with the service.

The return value of bindService() indicates whether the requested service exists and whether the client is permitted access to it.

When the Android system creates the connection between the client and service, it calls onServiceConnected() on the ServiceConnection. The onServiceConnected() method includes an IBinder argument, which the client then uses to communicate with the bound service.

ServiceConnection.onServiceConnected() 在未来某个时间点在 UI 线程上调用(不是在调用 Context.bindService() 之后立即),一旦连接到服务正确建立。

关于android - 究竟什么时候会调用有界服务的 onServiceConnected?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10802456/

74 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com