Android AIDL编程简例

参照 http://developer.android.com/guide/components/aidl.html

AIDL(Android Interface Definition Language),进程通信接口的描述语言。


1) 创建.aidl文件。

You must define your AIDL interface in an .aidl file using the Java programming language syntax, then save it in the source code (in the src/ directory) of both the application hosting the service and any other application that binds to the service.

使用eclipse新建android工程TestAIDLRemote,在src目录下添加一个包aidl,在其中创建RemoteAIDLService.aidl,如图:


在文件中使用java的语法定义接口,此处,接口名必须同aidl文件名相同:

package aidl;

interface RemoteAIDLService {

String RemoteServeGetName();

String RemoteServeGetTime();

}


2) 编译.aidl文件。

Eclipse自动编译生成对于的.java文件,在gen目录下,如图:



3) 实现接口方法。

The Android SDK tools generate an interface in the Java programming language, based on your .aidl file. This interface has an inner abstract class named Stub that extends Binder and implements methods from your AIDL interface. You must extend the Stub class and implement the methods.

创建一个RemoteService类,继承RemoteAIDLService.Stub类,并实现接口中定义的方法,代码如下:



4) 向client暴露接口。

Implement a Service and override onBind() to return your implementation of the Stub class.

如上所述,创建一个Service类,名为MyService,在其中创建类型为RemoteService的成员变量mRemoteService,重写onBind方法,返回mRemoteService:


别忘了再AndroidManifest.xml中注册这个Service:



5) 创建客户端,远程调用服务端暴露的aidl服务。

创建一个android工程,命名为TestAIDLClient。要使用服务端的aidl接口,客户端也必须具备与服务端相同的aidl文件,但是客户端不必实现接口,仅仅使用而已。

客户端可以使用bindService的方法获得服务端的IBinder,而这个IBinder正是服务端实现了的aidl接口,这样就可以使用aidl接口提供的服务了。

在TestAIDLClient的MainActivity中声明一个RemoteAIDLService接口mRemoteAIDLService,定义一个ServiceConnection对象mConnection并重写其中的onServiceConnected方法(该方法能够接受来自服务端返回的IBinder对象),把返回的IBinder转化为RemoteAIDLService接口,赋值给mRemoteAIDLService。

使用mRemoteAIDLService接口中的方法,调用服务端服务(代码在服务端执行,结果返回给客户端)。

客户端代码和运行效果如下图:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值