gpt4 book ai didi

java - Android 服务在启动/恢复时短暂为空

转载 作者:行者123 更新时间:2023-12-01 06:00:58 27 4
gpt4 key购买 nike

我有一个后台服务,用于管理第三方 API 的发布/订阅。

我这样设置服务:

 public ServiceConnection myServiceConn = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
myService = ((ThirdPartyService.Binder)binder).getService();
}
}

然后在我的 Activity onCreate 方法中:

Intent intent = new Intent(this, ThirdPartyService.class);
bindService(intent);

当 Activity 加载时,服务最初为空。

public void onStart() {
myService.doSomething(); //is null for a few hundred milliseconds
}

在使用该服务之前,我必须设置延迟(至少 500 毫秒)。

问题是,是否有一个回调方法/策略可以用来在服务可用时触发,而不是任意延迟?

最佳答案

当调用 onServiceConnected 回调时,该服务将可用,此时您可以保证 myService 变量不为 null。

之后只需触发需要使用 ThirdPartyService API 服务的所有内容即可。我还希望在 Activity 中定义 myServiceConn

关于java - Android 服务在启动/恢复时短暂为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59534911/

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