2011-03-09 131 views
0

我绑定到服务,使用context.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);。该方法返回true。但我没有联系。有些代码:Android绑定到服务

// Snippet from method, that connects to service: 
boolean result = context.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE); 
Log.d(TAG, "is connected: " + connected); 
return result; 
} 

// Connection: 
private ServiceConnection connection = new ServiceConnection() { 

     public void onServiceConnected(ComponentName name, IBinder service) { 
      parser = Parser.Stub.asInterface(service); 
      Log.d(TAG, "Connected to service..."); 
      connected = true; 
     } 

     public void onServiceDisconnected(ComponentName name) { 
      parser = null; 
      Log.d(TAG, "Disconnected from service..."); 
      connected = false; 
     } 

    }; 

最终,我没有进入onServiceConnected方法:在logcat中没有任何消息,除了D/FrameworkBridge( 926): is connected: false。 任何想法?

UPD:我在连接到它后立即调用服务方法(即抛出NPE),并且一切正常:服务已启动并绑定到该服务。似乎连接是在单独的线程中创建的,等等。有什么办法可以让我的课程等待,实际上建立连接吗?

回答

1

我跑了相同的问题,并发现我不得不打电话给startService以及得到它的工作:http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent

这是我的代码如下所示:

startService(new Intent(MainActivity.this, WeatherService.class)); 

bindService(new Intent(MainActivity.this, 
       WeatherService.class), mConnection, Context.BIND_AUTO_CREATE); 
+0

只是叫' context.startService(bindIntent);'在调用'bindService'方法之后。没有帮助,同样的问题。 – folone 2011-03-09 15:27:30

+0

在上面的答案中添加了我使用的代码。 – Christian 2011-03-09 19:02:39

+0

对我的代码进行了修改,使其与您的代码类似。仍然没有运气。我还从类中调用'startService'和'bindService',这不是'Activity',也没有它自己的'Context'。它是一个实用程序类,它接受'Context'作为构造函数参数,然后使用它来启动并绑定到服务。这可能是相关的吗? – folone 2011-03-10 08:06:07