前面介绍过注册Java Service的流程,这一章我们来看应用程序如何调用Java Service的接口。
Java Service的获取
在Java Service当中,会经常使用到AIDL工具,AIDL在google官方文档的解释是:"AIDL (Android Interface Definition Language) is similar to other IDLs you might have worked with. It allows you to define the programming interface that both the client and service agree upon in order to communicate with each other using interprocess communication (IPC)"。即AIDL是一种接口描述语言,用于定义client和service共同认可的接口。听起来比较绕口,直接来看IWifiManger.aidl的大致内容:
interface IWifiManager
{
List<WifiConfiguration> getConfiguredNetworks();
int addOrUpdateNetwork(in WifiConfiguration config);
boolean removeNetwork(int netId);
boolean enableNetwork(int netId, boolean disableOthers);
boolean disableNetwork(int netId);
boolean pingSupplicant();
void startScan(in WorkSource ws);
List<ScanResult> getScanResults(String callingPackage);
void disconnect();
void reconnect();
void reassociate();
这里定义了一系列的函数接口,在AIDL中除了支持Java原始类型数据(int、long、char、boolean等),还支持String、CharSequence、list和map。进过AIDL工具的转换,就可以将上面的aidl文件生成一个Java文件,其内容大致如下:
public interface IWifiManager extends android.os.IInterface {
public static abstract class Stub extends android.os.Binder implements
android.net.wifi.IWifiManager {
private static final java.lang.String DESCRIPTOR = "android.net.wifi.IWifiManager";
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
public static android.net.wifi.IWifiManager 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 android.net.wifi.IWifiManager))) {
return ((android.net.wifi.IWifiManager) iin);
}
return new android.net.wifi.IWifiManager.Stub.Proxy(obj);
}
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data,
android.os.Parcel reply, int flags)
throws android.os.RemoteException {
switch (code) {
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements android.net.wifi.IWifiManager {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
public android.os.IBinder asBinder() {
return mRemote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
}
IWifiManager.java中主要包含三个类:IWifiManager类、IWifiManager.Stub类、IWifiManager.Stub.Proxy类,WifiSerive就是继承于IWifiManager.Stub类。前面我们已经看过它的关系了,下面来看一般获取WifiService的方法:
IBinder b = ServiceManager.getService(WIFI_SERVICE);
IWifiManager service = IWifiManager.Stub.asInterface(b);