Does Binder have to be an inner class?

2019-09-04 13:03发布

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 ?

1条回答
放我归山
2楼-- · 2019-09-04 13:44

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.

查看更多
登录 后发表回答