: Beginning Android

Bound for Success

Bound for Success

To use a service, you first need to create an instance of your own ServiceConnection class. ServiceConnection, as the name suggests, represents your connection to the service for the purposes of making IPC calls. For example, here is the ServiceConnection from the WeatherPlus class in the WeatherPlus project:

private ServiceConnection svcConn =newServiceConnection() {
public voidonServiceConnected(ComponentName className,
IBinder binder) {
service = IWeather.Stub.asInterface(binder);
browser.postDelayed(newRunnable() {
public voidrun() {
}, 1000);
public voidonServiceDisconnected(ComponentName className) {
service =null;

Your ServiceConnection subclass needs to implement two methods:

1.onServiceConnected(), which is called once your activity is bound to the service

2.onServiceDisconnected(), which is called if your connection ends normally, such as you unbinding your activity from the service

Each of those methods receives a ComponentName, which simply identifies the service you connected to. More importantly, onServiceConnected() receives an IBinder instance, which is your gateway to the IPC interface. You will want to convert the IBinder into an instance of your AIDL interface class, so you can use IPC as if you were calling regular methods on a regular Java class (IWeather.Stub.asInterface(binder)).

To actually hook your activity to the service, call bindService() on the activity:

bindService(serviceIntent, svcConn, BIND_AUTO_CREATE);

The bindService() method takes three parameters:

1.An Intent representing the service you wish to invoke for your own service, its easiest to use an intent referencing the service class directly (new Intent(this, WeatherPlusService.class))

2.Your ServiceConnection instance

3.A set of flags most times, you will want to pass in BIND_AUTO_CREATE, which will start up the service if it is not already running

After your bindService() call, your onServiceConnected() callback in the ServiceConnection will eventually be invoked, at which time your connection is ready for use.

: 1.477. /Cache: 3 / 1