Listing 96 Binding to a Service Available for

download on // Reference to the service Wrax.com private MyService serviceBinder;

// Handles the connection between the service and activity private ServiceConnection mConnection = new ServiceConnection() {

public void onServiceConnected(ComponentName className, IBinder service) { // Called when the connection is made.

serviceBinder = ((MyService.MyBinder)service).getService();

public void onServiceDisconnected(ComponentName className) { // Received when the service unexpectedly disconnects. serviceBinder = null;

To perform the binding, call bindService, passing in an Intent (either explicit or implicit) that selects the Service to bind to and an instance of your new ServiceConnection implementation, as shown in this extension of Listing 9-6:

©Override public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState);

// Bind to the service

Intent bindIntent = new Intent(MyActivity.this, MyService.class); bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);

Once the Service has been bound, all of its public methods and properties are available through the serviceBinder object obtained from the onServiceConnected handler.

Android applications do not (normally) share memory, but in some cases your application may want to interact with (and bind to) Services running in different application processes.

You can communicate with a Service running in a different process using broadcast Intents or through the extras Bundle in the Intent used to start the Service. If you need a more tightly coupled connection you can make a Service available for binding across application boundaries using AIDL. AIDL defines the Service's interface in terms of OS level primitves, allowing Android to transmit objects across process boundaries. AIDL definitions are covered in Chapter 15.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment