Search code examples
androidandroid-serviceandroid-service-binding

Does Binder have to be an inner class?


I am reading upon Android Bound service, http://developer.android.com/guide/components/bound-services.html

public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();

/**
 * Class used for the client Binder.  Because we know this service always
 * runs in the same process as its clients, we don't need to deal with IPC.
 */
public class LocalBinder extends Binder {
    LocalService getService() {
        // Return this instance of LocalService so clients can call public methods
        return LocalService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

/** method for clients */
public int getRandomNumber() {
  return mGenerator.nextInt(100);
}

}

And all the tutorial, android developer guide and books suggest to have Binder as inner class of service. Is it really have to be only inner class ?


Solution

  • It is an inner class so you can return the outer Service instance easily. You could als make it an external class:

    public class LocalBinder extends Binder {
    
      private final LocalService mLocalService;
    
      public LocalBinder(final LocalService service) {
        mLocalService = service;
      }
    
      LocalService getService() {
        return mLocalService;
      }
    }
    

    Using an inner class saves you from the trouble of creating a field and a constructor.