我使用context.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);
绑定到服务。此方法返回true
。但我没有联系。一些代码:
// 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
方法:除了D/FrameworkBridge( 926): is connected: false
之外,logcat中没有消息。
有什么想法吗?
UPD:我在连接到服务方法后立即调用了服务方法(即投掷NPE),一切运行良好:服务启动并绑定到。似乎连接是在单独的线程中创建的,或者左右。有什么方法可以让我的课程等待,实际建立连接的实用程序是什么?
答案 0 :(得分: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);