Tuesday, August 26, 2014

Binding Activities to Services

When an Activity is bound to a Service, it maintains a reference to the Service instance itself, enabling you to make method calls on the running Service as you would on any other instantiated class.

To bind an Activity to a Service

In the Service

1) Declare an inner class that extends the Binder class.
2) Implement the getService() method in the inner class that return an instance of the service.
3) Create an instance of the inner class
4) Return this from the onBind() method of the Service

In the Activity

1) Declare an instance of the Service
2) Create an instance of the ServiceConnection to monitor the state of the service. ServiceConnection represents the connection between the Activity and the Service.
3) Override onServiceConnected() method which is called when the activity is connected to the service. Get the reference to the Service instance once a connection has been established.
4) Override onServiceDisconnected() method which is called when the service is disconnected from the activity.
5) Bind the Activity to the Service, before starting the Service, by calling the bindService() method.

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

private final IBinder binder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
   return binder;
}
public class MyBinder extends Binder {
   MyService getService() {
      return MyService.this;
   }
}

// Reference to the service
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
  • an instance of your new ServiceConnection implementation


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Bind to the service
    Intent bindIntent = new Intent(MyActivity.this, MyService.class);
    bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
}

Example

public class MyService extends Service {

URL[] urls;

    //Create an inner class that extends the Binder class
    public class MyBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }

//Create an instance of MyBinder that extends Binder
    private final IBinder binder = new MyBinder();
    
    //Return the instance of MyBinder
@Override
public IBinder onBind(Intent arg0) {
return binder;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) 
       {   ...
       }
}

public class ServiceActivity extends Activity {

//Acts as a reference to the service
    MyService serviceBinder;
    Intent i;

    //Instance of ServiceConnection is used to monitor the state of the service
    private ServiceConnection connection = new ServiceConnection() 
    {
   
    //Called when the activity is connected to the service
        public void onServiceConnected(ComponentName className, IBinder service) {
            //---called when the connection is made---
            serviceBinder = ((MyService.MyBinder)service).getService();
            try {
                URL[] urls = new URL[] {
                    new URL("http://www.amazon.com/somefiles.pdf"),
                    new URL("http://www.wrox.com/somefiles.pdf"),
                    new URL("http://www.google.com/somefiles.pdf"),
                    new URL("http://www.learn2develop.net/somefiles.pdf")};
                    //---assign the URLs to the service through the serviceBinder object---
                    serviceBinder.urls = urls;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }   
                startService(i);
        }
        
        //Called when the service is disconnected from the activity
        public void onServiceDisconnected(ComponentName className) {
            //---called when the service disconnects---
            serviceBinder = null;
        }
    };
    
    public void onClickButton(View view)
    {
    i = new Intent(ServiceActivity.this, MyService.class);
   
    //Before starting the service, bind the activity to the service
    //<intent object>, <ServiceConnection object>, <flag to indicate how the service should be bound>    
    bindService(i, connection, Context.BIND_AUTO_CREATE); 
    }
}

No comments:

Post a Comment