Android笔记三十.Service入门(四).跨进程调用Service(AIDL Servi

1.什么是AIDL Service?

AIDL,即Android Interface Definition Language.是Android用于定义远程接口,AIDL接口定义语言的语法比较简单,这种接口定义语言并不是真正的编程语言,它只是定义两个进程之间的通信接口。AIDL的语法与Java接口很相似,但存在如下几点差异:

(1)AIDL定义接口的源代码必须以.aidl结尾;

(2)AIDL接口中用到数据类型,除了基本类型、String、List、Map、CharSequence之外,其他类型全部都需要导包,即使他们在同一个包中也需要导包。

(3)定义好AIDL接口之后(如Song.aidl),ADT工具会自动在gen目录下生成相应的包,并生成一个Song.java接口,在该接口里包含一个Stub内部类,该内部类实现了IBinder、Song两个接口,这个Stub类将会作为远程Service的回调类。它内部能实现一些功能。

中,复制到客户端后ADT工具会为AIDL接口生成相应的Java接口类。

(interprocess communiocation,简称IPC),Android提供了AIDL Service。

2.远程Service

,因此,Android的AIDL远程接口的实现类就是那个IBinder实现类。当客户端获取了远程Service的IBinder对象的代理之后,客户端进程就可通过该IBinder对象去回调远程Service的属性或方法,从而实现进程间的通信。

3.Service返回的IBinder对象

当访问者(客户端)调用bindService()方法来绑定与启动指定的Service,对于绑定本地Service还是绑定远程Service,Service返回的IBinder对象是有所区别的。

(1)绑定本地Service:本地Service的onBind()方法会直接把IBinder对象本身传给客户端的ServiceConnection对象的onServiceConnected方法的第二个参数;

(2)绑定远程Service:远程Service的onBind()方法只是将IBinder对象的代理传给客户端的ServiceConnection对象的onServiceConnected方法的第二个参数。

4.AIDL接口工作原理

二、进程间通信开发思路

1.服务端-远程Service开发

package com.example.android_aidlservice;

interface ICat

{

String getColor();

double getWeight();

}

其中,com.example.android_aidlservice为其所在的包名。

注意:保存后,ADT工具会自动在gen/com.example.service目录下生成一个ICat.java接口

(2)定义一个Service实现类,并实现一个内q部类继承于Stub即实现了ICat接口,也就实现了IBinder接口。该Service的onBind()方法所返回的IBinder对象为ICat.Stub的子类的实例。

private CatBinder catBinder;

public class CatBinder extends Stub

{

……

}

@Override

public IBinder onBind(Intent arg0)

{

return catBinder;

}

(3)在AndroidMainfest.xml工程文件中配置该Service

<application ….>

<!–定义一个Service组件–>

<service android:name=".AidlService">

<intent-filter>

<action android:name="com.example.sercie.AIDL_SERVICE"></action>

</intent-filter>

</service>

</application>

2.客户端开发思路

(1)定义一个AIDL接口,文件名为xxx.aidl,保存到源码所在的路径,如/src/com/android_aidlservice/ICat.aidl;

package com.example.android_aidlservice;

interface ICat

{

String getColor();

double getWeight();

}

其中,com.example.android_aidlservice为其所在的包名,该.aidl文件为从Service段的AIDL接口文件复制到客户端应用中。

(2)创建ServiceConnection对象,并在ServiceConnection对象的onServiceConnected方法中添加如下代码:

catService = ICat.Stub.asInterface(service);

其中,catService为Service的onBind()方法返回IBinder对象的代理。

(3)以ServiceConnection对象作为参数,调用Context的bindService()方法绑定并启动远程Service即可。

(4)将返回的IBinder对象的代理类转换成IBinder对象,从而调用Service中的相应方法。

三、源码实现

1.服务端

(1)定义一个Service实现类-/src/com/example/android_service/AidlService.java

也不要说曾经失去,失去的不是永远失去,得到的不是永远拥有,

Android笔记三十.Service入门(四).跨进程调用Service(AIDL Servi

相关文章:

你感兴趣的文章:

标签云: