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

Rya*_*yan 45 service binding android serviceconnection

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

public class Downloader extends Activity {
 IDownloaderService downloader = null;
// ...
Run Code Online (Sandbox Code Playgroud)

在Downloader.onCreate(Bundle)中,我尝试使用bindService

Intent serviceIntent = new Intent(this, DownloaderService.class);
if (bindService(serviceIntent, sc, BIND_AUTO_CREATE)) {
  // ...
Run Code Online (Sandbox Code Playgroud)

在ServiceConnection对象sc中,我做到了这一点

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

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

另一个问题有关.是所有的事件处理程序:Activity.onCreate,任何View.onClickListener.onClick,ServiceConnection.onServiceConnected等实际在同一个线程中调用(在文档中提到的"主线程")?它们之间是否存在交错,或Android会安排所有事件逐个处理?或者,究竟什么时候实际上要调用ServiceConnection.onServiceConnected?完成Activity.onCreate或A.oC仍在运行时?

Com*_*are 52

如何可靠地等待ServiceConnection.onServiceConnected被调用?

你没有.退出onCreate()(或绑定的任何地方)并且您将"需要建立连接"代码放入其中onServiceConnected().

是所有事件处理程序:Activity.onCreate,任何View.onClickListener.onClick,ServiceConnection.onServiceConnected等实际在同一个线程中调用

是.

究竟什么时候实际上要调用ServiceConnection.onServiceConnected?完成Activity.onCreate或A.oC仍在运行时?

您的绑定请求可能在您离开之后才开始onCreate().因此,onServiceConnected()你离开后的某个时候会打电话onCreate().

  • 虽然我可以理解onCreate()必须在onServiceConnected()开始之前完成(我猜它在主线程Looper中待定),我注意到onStart()和onResume()也在onServiceConnected()之前运行!这不是一个危险的竞争条件吗?查看依赖于服务的组件已准备就绪,但服务尚未连接. (21认同)
  • @jfritz42那是问题不是吧..为什么Android没有给我们一个同步版本的bind? (4认同)
  • 感谢您提供此信息.希望Android文档可以像这样清楚. (3认同)
  • 各种Service API演示都有示例; 特别参见本地服务绑定和远程服务绑定:http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/index.html服务java doc也有样本本地服务绑定的代码:http://developer.android.com/reference/android/app/Service.html#LocalServiceSample (2认同)