Android绑定到服务
我使用Android绑定到服务,android,service,ipc,Android,Service,Ipc,我使用context.bindService(bindIntent,connection,context.BIND\u AUTO\u CREATE)绑定到一个服务。此方法返回true。但我没有联系上。一些代码: // Snippet from method, that connects to service: boolean result = context.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE); Log.d(
context.bindService(bindIntent,connection,context.BIND\u AUTO\u 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),并且一切正常:服务启动并绑定到。似乎连接是在一个单独的线程中创建的,或者说。有什么方法可以让我的类等待,直到连接真正建立起来吗?我遇到了同样的问题,发现我也必须调用startService才能使其工作:)
这就是我的代码的样子:
startService(new Intent(MainActivity.this, WeatherService.class));
bindService(new Intent(MainActivity.this,
WeatherService.class), mConnection, Context.BIND_AUTO_CREATE);
刚刚调用了context.startService(bindIntent)代码>在调用bindService
方法之后。没有帮助,同样的问题。对我的代码进行了修改,使其与您的代码相似。还是不走运。我还在类中调用startService
和bindService
,这不是活动
,也没有自己的上下文
。它是一个实用类,接受上下文
作为构造函数参数,然后使用它启动并绑定到服务。这有关系吗?