目录
第一步:在需要提供服务的module里定义aidl文件
在src/main下新建aidl文件夹,然后新建目录,创建aidl文件,比如"IWifiApInterface.aidl"文件,编译后会在"build\generated\aidl_source_output_dir\debug\out"目录下生成IWifiApInterface.java,它会有一个内部类Stub继承Binder。
第二步:定义Binder类
定义WifiApBinder类,继承IWifiApInterface.Stub,实现aidl文件里定义的方法.
第三步:定义Service类
在Service里创建自定义的Binder类WifiApBinder,复写onBind方法返回WifiApBinder的实例。
声明服务:注意声明exported="true",定义action。
<application>
<service
android:name=".service.WifiApService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.voyah.settings.hotspot.wifiapservice"/>
</intent-filter>
</service>
</application>
第四步:创建对外提供服务的sdk module
将aidl文件拷贝过来,定义服务工具类,继承extends IWifiApInterface.Stub,并编写绑定服务、解绑服务的方法。
- 绑定服务
connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iWifiApInterface = IWifiApInterface.Stub.asInterface(service);
isConnected = true;
Log.d(TAG, "onServiceConnected: 热点服务连接成功");
}
@Override
public void onServiceDisconnected(ComponentName name) {
isConnected = false;
Log.d(TAG, "onServiceDisconnected: 热点服务连接断开");
}
@Override
public void onBindingDied(ComponentName name) {
Log.e(TAG, "onBindingDied: " + name);
isConnected = false;
}
};
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.voyah.setting", "com.voyah.settings.hotspot.service.WifiApService"));
boolean code = context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
- 解绑服务
if (isConnected) {
mContext.unbindService(connection);
}
- 实现aidl里的方法
通过调用iWifiApInterface对象,实现aidl定义的各个方法。
0 条评论