相关疑难解决方法(0)

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

我有一个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仍在运行时?

service binding android serviceconnection

45
推荐指数
1
解决办法
4万
查看次数

标签 统计

android ×1

binding ×1

service ×1

serviceconnection ×1