我的理解是,如果我想要一个服务运行,即使没有绑定到它,那么它必须首先使用startService(Intent i)启动。
我的问题是,如果我想在启动服务后立即绑定到它,下面的代码能保证服务是用startService()创建的吗?
服务类中的静态方法:
public static void actStart(Context ctx) {
Intent i = new Intent(ctx, BGService.class);
i.setAction(ACTION_START);
ctx.startService(i);
}绑定活动:
BGService.actionStart(getApplicationContext());
bindService(new Intent(this, BGService.class), serviceConnection, Context.BIND_AUTO_CREATE);发布于 2012-06-26 16:49:10
我不知道你在这里想做什么,但是"Context.BIND_AUTO_CREATE“创建服务,然后绑定到服务,即使它还没有启动。
现在,如果您想在绑定后立即访问它,可以使用serviceConnection的onServiceConnected()方法:
new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
//put your code here...
} ...发布于 2014-01-05 01:14:14
为了补充Bugdayci的答案,一个完整的例子如下:
ServiceConnection myConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
... your code that needs to execute on service connection
}
@Override
public void onServiceDisconnected(ComponentName name) {
... your code that needs to execute on service disconnection
}
};
Intent intent = new Intent(this, TheServiceClassName.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);..。
如果末尾没有bindService,onServiceConnected()代码将不会执行。
https://stackoverflow.com/questions/6896161
复制相似问题