2、绑定AIDL服务获取远程接口对象
<p><strong>绑定源码可以参考多国语言打印项目中的aidl绑定,多国语言项目提供的Android Studio和Eclipse两个版本项目下载,根据实际需求下载使用。<a href="http://doc.szzkc.com/web/#/3?page_id=47">http://doc.szzkc.com/web/#/3?page_id=47</a></strong></p>
<p>& 绑定服务前,需确保设备已经安装好正确的服务程序,可用提供的测试程序先行测试,在测试的过程中发现任何问题请及时联系服务程序提供者。</p>
<h4>定义服务连接监听对象ServiceConnection</h4>
<p>//服务接口对象,服务连接成功后会返回该对象。
//Service interface object, the object will be return after the connection is successful</p>
<hr />
<pre><code> public static IZKCService mIzkcService;
private ServiceConnection mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(&quot;client&quot;, &quot;onServiceDisconnected&quot;);
mIzkcService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(&quot;client&quot;, &quot;onServiceConnected&quot;);
/**
服务绑定成功,获取到该服务接口对象,可通过该接口调用相关的接口方法来完成相应的功能
*success to get the sevice interface object
*/
mIzkcService = IZKCService.Stub.asInterface(service);
}
}
};</code></pre>
<hr />
<h4>绑定服务</h4>
<p>//com.zkc.aidl.all 为远程服务的名称,<strong>不可更改</strong>
//com.smartdevice.aidl为远程服务声明所在的包名,<strong>不可更改</strong>,
//对应的项目所导入的AIDL文件也应该在该包名下</p>
<hr />
<pre><code> Intent intent = new Intent(&quot;com.zkc.aidl.all&quot;);
intent.setPackage(&quot;com.smartdevice.aidl&quot;);
bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE);</code></pre>
<hr />
<h4>解绑服务</h4>
<hr />
<p>//退出程序之前,需要解除已绑定的服务。
unbindService(mServiceConn);</p>