Does Binder have to be an inner class?

百般思念 提交于 2020-01-25 20:25:07

问题


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:


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.



来源:https://stackoverflow.com/questions/33030969/does-binder-have-to-be-an-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!