我在 onCreate() 中启动我的服务(如果第一次调用 onCreate)并在 onStart() 中调用 bindService。该服务可能有效,但在调用 bindService 后,我的本地服务实例仍然为空。此外,似乎没有调用 getService() 。?这是一些代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
if(savedInstanceState == null){
final Intent i = new Intent(this, HostService.class);
startService(i);
}
}
protected void onStart(){
super.onStart();
bindService(new Intent(this, StartGameActivity.class), connection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection connection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
HostBinder binder = (HostBinder) arg1;
hostService = binder.getService();
isBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
在 HostService 中:
...
private HostBinder binder = new HostBinder();
...
public class HostBinder extends Binder{
HostService getService(){
Log.d(TAG, "getService");
return HostService.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
return binder;
}
为什么在调用 onStart() 之后 hostService 仍然为空,为什么 getService 没有被调用(“getService”不在 LogCat 中打印)?
谢谢和问候