gpt4 book ai didi

Android如何等到服务实际连接?

转载 作者:IT王子 更新时间:2023-10-28 23:52:44 25 4
gpt4 key购买 nike

我有一个 Activity 调用 IDownloaderService.aidl 中定义的服务:

public class Downloader extends Activity {
IDownloaderService downloader = null;
// ...

在 Downloader.onCreate(Bundle) 我尝试绑定(bind)服务

Intent serviceIntent = new Intent(this, DownloaderService.class);
if (bindService(serviceIntent, sc, BIND_AUTO_CREATE)) {
// ...

在 ServiceConnection 对象 sc 中我这样做了

public void onServiceConnected(ComponentName name, IBinder service) {
Log.w("XXX", "onServiceConnected");
downloader = IDownloaderService.Stub.asInterface(service);
// ...

通过添加各种 Log.xx 我发现 if(bindService(...)) 之后的代码实际上是在调用 ServiceConnection.onServiceConnected 之前 - 也就是说,当下载器仍然为空时 - 这让我遇到了麻烦. ApiDemos 中的所有示例都通过仅在用户操作触发时调用服务来避免此时间问题。但是在bindService成功后我应该怎么做才能正确使用这个服务呢?如何等待 ServiceConnection.onServiceConnected 被可靠调用?

另一个相关的问题。是否所有事件处理程序:Activity.onCreate、任何 View.onClickListener.onClick、ServiceConnection.onServiceConnected 等实际上都在同一个线程中调用(在文档中称为“主线程”)?它们之间是否存在交错,或者 Android 会安排所有事件一一处理?或者,实际上何时调用 ServiceConnection.onServiceConnected?在 Activity.onCreate 完成时或 A.oC 仍在运行时?

最佳答案

How can I wait for ServiceConnection.onServiceConnected being called reliably?

你没有。你退出 onCreate() (或任何你绑定(bind)的地方),你把你“需要建立连接”的代码放在 onServiceConnected() 中。

Are all the event handlers: Activity.onCreate, any View.onClickListener.onClick, ServiceConnection.onServiceConnected, etc. actually called in the same thread

是的。

When exactly is ServiceConnection.onServiceConnected actually going to be called? Upon completion of Activity.onCreate or sometime when A.oC is still running?

在您离开 onCreate() 之前,您的绑定(bind)请求可能甚至不会开始。因此,onServiceConnected() 将在您离开 onCreate() 后的某个时间调用。

关于Android如何等到服务实际连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3055599/

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