Android Service那些不得不说的事-之二(Bound Service的实现方式)

本文详细介绍了Android中Bound Service的实现方式,特别是通过onBind()返回自定义Binder或使用AIDL来实现客户端与服务端的交互。强调了不同方式的优缺点,如自定义Binder的简单使用但限制在同一进程内,而AIDL则支持跨进程通信,但增加了复杂性。在调用service的方法时,自定义Binder直接在当前线程执行,而AIDL则在binder线程执行。
摘要由CSDN通过智能技术生成

To provide binding for service, you must implement the onBind() method. This method returns anIBinder object that defines the interface that clients can use to interact with the service.

三种不同的方式,说白了就是通过onBind()返回三种不同类型的IBinder object。

一、可以返回自定义的Binder(继承自Binder),并且在其中提供public methods that the client can call

通常情况下,we returns the current Service instance, or an instance of another class hosted by the service with public methods theclient can call.

private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }

优点:

1. 使用简单,client在onServiceConnected()拿到Binder之后,可以直接cast到原本的类型,进行使用。

缺点:

1. 必须在同一个进程中使用,因为一般自定义的Binder不会按照IPC的要求实现Binder中的接口,如何支持IPC,请参看AIDL实现的Binder类。

注意:

1. 此种方法调用service的function时,就跟一个普通的函数调用一样,在当前线程执行,而不像IPC那样,service端的function都是在binder thread中执行。

三、使用AIDL,onBind()返回ServiceInterface.Stub mBinder = new ServiceInterface.Stub(){ }。

编译工具会根据.aidl文件生成一个.java文件,里面有AIDL实现的Binder类。例如,我们提供的.aild文件如下:

package com.baidu.test.aidl;
import com.baidu.test.aidl.ClientInterface;

interface ServiceInterface {  
    void register(ClientInterface client);  
    void serviceFun();
    void invokeClientCallBack();
}

系统帮我们生成的.java文件如下:

package com.baidu.test.aidl;

public interface ServiceInterface extends android.os.IInterface {
    public void register(com.baidu.test.aidl.ClientInterface client) throws android.os.RemoteException;
    public void serviceFun() throws android.os.RemoteException;
    public void invokeClientCallBack() throws android.os.RemoteException;

    // ========================  Stub用在service端  ================================
    public static abstract class Stub extends android.os.Binder implements com.baidu.test.aidl.ServiceInterface {
        private static final java.lang.String DESCRIPTOR = "com.baidu.test.aidl.ServiceInterface";
        
        static final int TRANSACTION_register = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
        static final int TRANSACTION_serviceFun = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
        static final int TRANSACTION_invokeClientCallBack = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
        
        public Stub() {
            // from Binder, Convenience met
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值