Bound services
Once a sticky service is started, it is “on” until a component calls Context.stopService(Intent). If
the service needs to be killed for some reason, it will be restarted again with a null intent passed into
onStartCommand(...).
A sticky service may be appropriate for a long-running service, like a music player, which needs to
stick around until the user tells it to stop. Even then, it is worth considering an alternative architecture
using non-sticky services. Sticky service management is inconvenient, because it is difficult to tell
whether the service is already started.
Bound services
In addition to all this, it is possible to bind to a service by using the bindService(Intent,
ServiceConnection, int) method. This allows you to call methods on the service directly.
ServiceConnection is an object that represents your service binding and receives all binding
callbacks.
In a fragment, your binding code would look something like this:
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
// Used to communicate with the service
MyBinder binder = (MyBinder)service;
}
public void onServiceDisconnected(ComponentName className) {
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = new Intent(getActivity(), MyService.class);
getActivity().bindService(i, mServiceConnection, 0);
}
@Override
public void onDestroy() {
super.onDestroy();
getActivity().unbindService(mServiceConnection);
}
On the service’s side, binding introduces two additional lifecycle callbacks:
- onBind(Intent) – called every time the service is bound to and returns the IBinder object
received in ServiceConnection.onServiceConnected(ComponentName, IBinder) - onUnbind(Intent) – called when a service’s binding is terminated
Local service binding
So what does MyBinder look like? If the service is a local service, then it may be a simple Java object
that lives in your local process. Usually this is used to provide a handle to directly call methods on your
service: