活页夹必须是一个内部阶级吗? [英] Does Binder have to be an inner class?

查看:147
本文介绍了活页夹必须是一个内部阶级吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Android Bound服务, http://developer.android. com/guide/components/bound-services.html

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);
}

}

所有教程,Android开发人员指南和书籍都建议将Binder作为内部服务类.真的只需要内部类吗?

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 ?

推荐答案

这是一个内部类,因此您可以轻松地返回外部Service实例.您也可以将其设置为外部类:

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.

这篇关于活页夹必须是一个内部阶级吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆