개발모음집

한 액티비티에서 하나의 서비스를 언바인딩하고 다시 바인딩하는 방법 (binding again after service unbinding) 본문

Android

한 액티비티에서 하나의 서비스를 언바인딩하고 다시 바인딩하는 방법 (binding again after service unbinding)

void 2018. 4. 20. 09:00

onDestory에서 unbinding 해주는 것뿐만 아니라 stopService를 해줘야 한다.

그리고 onCreate할 때 bindingService뿐만 아니라 startService를 해줘야 한다.



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
serviceIntent = new Intent(this, ChatService.class);
startService(serviceIntent);

Intent intent = new Intent(ChatRoomActivity.this, ChatService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

}


@Override
protected void onDestroy() {
unbindService(mConnection);
stopService(serviceIntent);
super.onDestroy();
}

 

It's actually possible to do both: bind to a Service and explicitly start and stop it. Binding to a service is particularly useful only if you need to share data from the Service to the Activity/other Context it is bound to. It sounds like for your needs, you want to use startService() and stopService() to control the lifecycle of your Service. If you still need to pass data back, then you can also bindService() after creating it with the startService() method.

참고 : stackOverflow