0

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 ?

Dave
  • 67
  • 1
  • 5
  • 1
    no, it doesn't have to be an inner class, you can make it as a "normal" class and implement "client methods" here – pskink Oct 09 '15 at 07:01

1 Answers1

0

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.

nhaarman
  • 98,571
  • 55
  • 246
  • 278
  • Would that be consider circular dependency ? As LocalService will need LocalBinder and LocalBinder will need LocalService. – Dave Oct 09 '15 at 06:13
  • 1
    you do not need `LocalService` in `LocalBinder` at all, so in most cases no need for `getService()` method – pskink Oct 09 '15 at 06:32