使用AIDL实现进程间的通信

本文介绍了在Android中使用AIDL进行进程间通信的基本流程。通过创建AIDL接口定义服务,实现接口的Stub类,配置Service,并在客户端进行连接和调用,展示了如何利用AIDL进行跨进程通信。
摘要由CSDN通过智能技术生成

在Android中,如果我们需要在不同进程间实现通信,就需要用到AIDL技术去完成。

AIDL(Android Interface Definition Language)是一种接口定义语言,编译器通过*.aidl文件的描述信息生成符合通信协议的Java代码,我们无需自己去写这段繁杂的代码,只需要在需要的时候调用即可,通过这种方式我们就可以完成进程间的通信工作。关于AIDL的编写规则我在这里就不多介绍了,读者可以到网上查找一下相关资料。

接下来,我就演示一个操作AIDL的最基本的流程。

首先,我们需要建立一个服务端的工程,如图所以:

 

在IPerson.aidl中我们定义了一个“问候”的方法,代码如下:

package com.scott.aidl;
interface IPerson {
    String greet(String someone);
}
在Eclipse插件的帮助下,编译器会自动在gen目录中生成对应的IPerson.java文件,格式化后的代码如下:

package com.scott.aidl;

public interface IPerson extends android.os.IInterface {
    /** Local-side IPC implementation stub class. */
    public static abstract class Stub extends android.os.Binder implements com.scott.aidl.IPerson {

        private static final java.lang.String DESCRIPTOR = "com.scott.aidl.IPerson";

        /** Construct the stub at attach it to the interface. */
        public Stub() {
            this.attachInterface(this, DESCRIPTOR);
        }

        /**
         * Cast an IBinder object into an com.scott.aidl.IPerson interface,
         * generating a proxy if needed.
         */
        public static com.scott.aidl.IPerson asInterface(android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = (android.os.IInterface) obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.scott.aidl.IPerson))) {
                return ((com.scott.aidl.IPerson) iin);
            }
            return new com.scott.aidl.IPerson.Stub.Proxy(obj);
        }

        public android.os.IBinder asBinder() {
            return this;
        }

        @Override
        public boolean onTransact(int code, an
评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值