在Android Studio中使用AIDL实现进程之间的通信

为了确保我写的服务在需要的时候一直运行在后台,我用到了守护进程机制,但是这样又出现了新的问题:两个进程不能调用同一个实例。

1、创建AIDL文件

通过写测试程序,aidl文件所在的包名可以与AndroidMainifest.xml文件的package名不一致

在IServiceAidlInterface.aidl文件中我定义了三个方法:

// IServiceAidlInterface.aidl
package com.yjn.cyclingworld;

// Declare any non-default types here with import statements
import java.util.List;
import com.yjn.cyclingworld.bean.CyclingData;
import com.yjn.cyclingworld.AIDLCallBack;

interface IServiceAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
     List<CyclingData> getCyclingData();

     void registerClient(AIDLCallBack cb);

     void unregisterClient();
}

其中getCyclingData()方法是获取自定义的CyclingData类的对象,所以必须导入该类的aidl文件。而CyclingData.java文件早就在java文件夹下的com.yjn.cyclingworld.bean包创建好了,所以CyclingData.aidl文件也创建在aidl文件夹中相同的包名下。还有两个方法是实现对客户端的调用。

// CyclingData.aidl
package com.yjn.cyclingworld.bean;

// Declare any non-default types here with import statements
//import com.yjn.cyclingworld.bean.CyclingData;

parcelable CyclingData;

跨进程通信传输的自定义的类必须先序列化,我把CyclingData.java类实现了Parcelable接口,在CyclingData.aidl文件中还需要声明parcelable CyclingData。

2、在Service类中实现AIDL接口

private final IBinder lib = new IServiceAidlInterface.Stub() {

    @Override
    public List<CyclingData> getCyclingData() throws RemoteException {
        return mCyclingDatas;
    }

    @Override
    public void registerClient(AIDLCallBack cb) throws RemoteException {
        LogUtil.e(TAG,"registerClient");
        client = cb;
    }

    @Override
    public void unregisterClient() throws RemoteException {
        LogUtil.e(TAG,"unregisterClient");
        client = null;
    }
};

3、在需要与Service通信的类中实现ServiceConnection接口,就可以使用IServiceAidlInterface.aidl文件里定义的接口了

private class ServiceConnect implements ServiceConnection {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mCyclingWorldService = IServiceAidlInterface.Stub.asInterface(service);
        try {
            mCyclingWorldService.registerClient(cb);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mCyclingWorldService = null;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zoipuus

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值