AIDL接口描述语言的使用

来源:互联网 发布:淘宝店商品图片制作 编辑:程序博客网 时间:2024/05/22 03:09

Android进程之间如何通讯呢?在Windows系统中存在IPC管道服务、MailSolt邮槽、消息等方法,在Android平台上提供了一种中间层语言AIDLAndroid接口定义语言(Android Interface Definition Language)。

使用方法:已AidlDemoClient(client)带用AidlDemo(server)中的服务为例子

1.在AidlDemo中建立一个.aidl文件

DemoService.aidl

package com.pekall.aidl;interface DemoService{void write(String content);}
eclipse会在gen文件夹中生成对应的DemoService.java文件

AIDL语法很简单,可以用来声明一个带一个或多个方法的接口,也可以传递参数和返回值。由于远程调用的需要, 这些参数和返回值并不是任何类型.下面是些AIDL支持的数据类型: 
(1). 不需要import声明的简单Java编程语言类型(int,boolean等) 

(2). String, CharSequence不需要特殊声明

(3). List, Map和Parcelables类型, 这些类型内所包含的数据成员也只能是简单数据类型, String等其他比支持的类型.

(4). 自定义的实体需要实现Parcelable接口


2.写一个类继承DemoService的子类Stub

DemoBinder.java

package com.pekall.aidlDemo;import android.os.RemoteException;import android.util.Log;import com.pekall.aidl.DemoService;public class DemoBinder extends DemoService.Stub{@Overridepublic void write(String content) throws RemoteException {Log.e("AIDL", content);}}

实例你的方法

3.写一个Service类供其他程序调用

IService.java

package com.pekall.aidlDemo;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class IService extends Service {private DemoBinder binder = new DemoBinder();@Overridepublic IBinder onBind(Intent intent) {return binder;}}

4.在清单文件(AndroidManifest.xml)中定义Service并提供供其他工程调用的隐式意图(内容自定义)

AndroidManifest.xml

<service android:name=".IService"><intent-filter><action android:name="com.pekall.aidl.IService"/></intent-filter></service>

5.建立客户端程序,并把服务端aidl所在的包和aidl文件共同拷贝到客户端工程

6.写前台程序调用此服务

Client.java

package com.pekall.aidlclient;import com.pekall.aidl.DemoService;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.util.Log;public class Client extends Activity {private DemoService demoService ;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);bindService(new Intent("com.pekall.aidl.IService"), connection, BIND_AUTO_CREATE);}@Overrideprotected void onDestroy() {super.onDestroy();unbindService(connection);}private ServiceConnection connection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {demoService = null;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {demoService = DemoService.Stub.asInterface(service);try {demoService.write("AIDL_DEMO");} catch (RemoteException e) {Log.e("Client", e.toString());e.printStackTrace();}}};}

7.先启动服务,在运行客户端,测试。



原创粉丝点击