我有一个活动调用 IDownloaderService.aidl 中定义的服务:
public class Downloader extends Activity {
IDownloaderService downloader = null;
// ...
在 Downloader.onCreate(Bundle) 中我尝试绑定Service
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 仍在运行时?