Android 绑定服务
我使用 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
方法:logcat 中没有消息,除了 D/FrameworkBridge( 926): is connect: false
。 有什么想法吗?
UPD: 在连接到服务方法后,我评论了立即调用服务方法(抛出 NPE),并且一切正常:服务已启动并绑定到。似乎连接是在单独的线程中创建的,等等。有什么方法可以让我的班级等待,直到连接实际建立?
I'm binding to a Service, using context.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);
. This method returns true
. But I don't get connected. Some code:
// 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;
}
};
Eventually, I don't get into onServiceConnected
method: no messages in logcat except for D/FrameworkBridge( 926): is connected: false
.
Any ideas?
UPD: I commented immediate call to service method (that was throwing NPE) after I connect to it, and everything worked well: the service is started and binded to. Seems like the connection is created in a separate thread, or so. Is there any way I can make my class wait, util the connection is actually established?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我遇到了同样的问题,发现我还必须调用 startService 才能使其正常工作: http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)
这就是我的代码的样子喜欢:
I ran in to the same issue and found out that I had to call startService as well to get it working: http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)
This is what my code looks like: