本文介绍的是一个AIDL服务程序,向客户端提供通过股票名称查询价格的服务。分别通过服务器端和客户端的代码向大家介绍。
在服务器端,我们要做如下事情:
1、编写一个AIDL文件向客户端定义接口(AIDL文件遵循Java语法,并以.aidl为文件扩展名。AIDL文件内部使用的包名要与Android项目包名相同) 。代码如下:
package cn.coresun.service; interface IStockQuoteService{ double getQuote(String name); }
2、AIDL文件写好后,如果没有错误。ADT插件会通过此AIDL文件生成Java源文件,此Java源文件我们不能修改,但是有几点要了解:
(1)此文件内定义了IStockQuoteService接口,此接口继承android.os.IInterface接口。
public interface IStockQuoteService extends android.os.IInterface
(2)在IStockQuoteService接口内定义了一个抽象类Stub,此类继承android.os.Binder类,并实现IStockQuoteService接口。
public static abstract class Stub extends android.os.Binder implements cn.coresun.service.IStockQuoteService
(3)在IStockQuoteService接口内定义了一个类Proxy,此类实现了IStockQuoteService接口,此类是Stub的代理类。
private static class Proxy implements cn.coresun.service.IStockQuoteService
3、编写服务类StockQuoteService.
(1)此类继承android.app.Service
(2)重写onCreate()和onDesdroy() 如果有事情做的话
(3)定义内部类StockQuoteServiceImple继承IStockQuoteService.Stub并实现服务方法getQuote(String name)
private class StockQuoteServiceImple extends IStockQuoteService.Stub{ public double getQuote(String name) throws RemoteException {
return 100.0; } }//此方法简单实现
(4)重写 IBinder onBind(Intent intent)方法,生成StockQuoteServiceImple对象并返回
public IBinder onBind(Intent arg0) { return new StockQuoteServiceImple(); }
Stub继承Binder,Binder实现IBinder,StockQuoteServiceImple继承Stub,故StockQuoteServiceImple间接实现IBinder。
4、AndroidManifest.xml文件如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.coresun.service" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <service android:name="StockQuoteService"> <intent-filter> <action android:name="cn.coresun.service.StockQuoteService"/> </intent-filter> </service> </application> </manifest>