Binder类是什么?在Android绑定服务中,绑定的含义是什么?

16
我对绑定服务完全感到困惑。我的问题是:
  • 什么是绑定?
  • Binder类是做什么的?
  • "返回可用于与服务交互的IBinder"是什么意思?
  • 什么是IBinder对象?
  • onBind()方法如何工作?
这些都是关于绑定服务的问题。请详细解释一下。我已经阅读了文档,但对我来说仍然不清楚。
2个回答

20

绑定服务:

绑定服务允许应用程序组件通过调用bindService()方法来创建长期连接并与之绑定。当您想从应用程序中的活动和其他组件与服务进行交互,或者通过进程间通信(IPC)向其他应用程序公开应用程序功能时,请创建绑定服务。

要创建绑定服务,请实现onBind()回调方法以返回定义与服务通信接口的IBinder。其他应用程序组件可以通过调用 bindService() 方法来检索该接口,并开始在服务上调用方法。服务仅存在于绑定到它的应用程序组件的生命周期内,因此当没有组件绑定到服务时,系统将销毁该服务。您不需要像启动onStartCommand()服务时那样停止绑定服务。

IBinder:

要创建绑定服务,必须定义指定客户端如何与服务通信的接口。这个服务和客户端之间的接口必须是IBinder的一个实现,并且必须从onBind()回调方法中返回。客户端接收到IBinder之后,就可以通过该接口开始与服务进行交互。

onBind():

当另一个组件想要绑定服务(例如执行RPC)时,系统会通过调用bindService()方法来调用此方法。在此方法的实现中,您必须提供客户端用于与服务通信的接口,并返回IBinder。您必须始终实现此方法;但是,如果您不想允许绑定,则应返回null。


1
一个实际的代码示例会更好,以配合这个复制粘贴。 - lasec0203

7

这是上面答案的一个例子

  1. 在你的服务类中,使用我们内部类创建的对象来初始化 IBinder 接口(参见步骤2)。
  2. 创建一个继承 Binder 的内部类,该内部类具有getter函数,以访问服务类。
  3. 覆盖你的服务类中的 onBind 函数,并使用它返回我们在步骤1中创建的实例。

**代码将为您清晰地解释**

public class MyServiceClass extends Service {

//binder given to client  
private final IBinder mBinder = new LocalBinder();

//our inner class 
public LocalBinder extends Binder {
public MyServiceClass getService() {
        return MyServiceClass.this;
    }
}
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

public void doSomeWork(int time){ //we will call this function from outside, which is the whole idea of this **Binding**}

  }

下一步是自身绑定。在您想要绑定服务的 MainClass 或其他地方,进行服务绑定。
  1. Defines callbacks for service binding, passed to bindService()

    private ServiceConnection serviceConnection = new ServiceConnection(){

    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
       MyServiceClass.LocalBinder binder =(MyServiceClass.LocalBinder)service;
       timerService = binder.getService();
    }
    
    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        //what to do if service diconnect
    }
    

    };

  2. the moment of binding

    Intent intent = new Intent(this, MyServiceClass.class);
    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    
解绑服务。
unbindService(serviceConnection);
  1. then you call the public function we created before in the Service class using the help of [timerService = binder.getService();]
    timerService.doSomeWork(50);
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接