Art*_*ans 43 android bluetooth bluetooth-lowenergy
Android的蓝牙低功耗API实现1种方法连接到该设备connectGatt()
,但2种方法来关闭连接disconnect()
和close()
.
文件说:
disconnect()
:断开已建立的连接,或取消当前正在进行的连接尝试.
close()
:应用程序应在使用此GATT客户端完成后尽早调用此方法.
BluetoothGatt.java的源代码显示close()取消注册应用程序,disconnect()断开客户端连接.然而,它没有说明实际意味着什么.我的意思是,如果只有一种方法可以连接到客户端,为什么有两种方法可以关闭/断开连接?
Dou*_*nes 66
随后disconnect()
您可以调用connect()
并继续该循环.
一旦打电话,close()
你就完成了.如果您想再次连接,你将不得不调用connectGatt()
上BluetoothDevice
再次; close()
将释放所持有的任何资源BluetoothGatt
.
Dro*_*ris 13
这是一些值得思考的东西:
只要你没有在Gatt上打电话,你仍然可以尝试连接它或发现.因此,当我尝试为机器发现服务时,我通常会运行一个线程或runnable,使请求连接到机器一段时间.
第一次使用机器连接尝试将返回一个BluetoothGatt对象,您可以在以后使用该对象尝试发现BluetoothDevice对象的服务.它似乎很容易连接,但更难发现机器的服务.
mBluetoothGatt = machine.getDevice().connectGatt(this, false, mGattCallback);
Run Code Online (Sandbox Code Playgroud)
所以在我的线程/ runnable中,我将检查BluetoothGatt是否为空.如果是,我将再次调用上面的代码行,否则我将尝试发现BluetoothGatt服务.
mBluetoothGatt.discoverServices();
Run Code Online (Sandbox Code Playgroud)
哦,我总是确保在尝试连接发现服务之前调用BluetoothAdapter.cancelDiscovery().
mBluetoothAdapter.cancelDiscovery();
Run Code Online (Sandbox Code Playgroud)
这是一个方法用于连接我的runnable等:
public void connectToMachineService(BLEMachine machine) {
Log.i(SERVICE_NAME, "ATTEMPTING TO CONNECT TO machine.getDevice().getName());
mBluetoothAdapter.cancelDiscovery();
if(mBluetoothGatt == null)
mBluetoothGatt = machine.getDevice().connectGatt(this, false, mGattCallback);
else
mBluetoothGatt.discoverServices();
}
Run Code Online (Sandbox Code Playgroud)
最后,确保关闭所有已连接的BluetoothGatt对象.似乎Android可以在开始说"无法连接到Gatt服务器"或其他类似的东西之前处理五个BluetoothGatt对象.
在我创建的每个BluetoothGatt上,我将在其上调用close然后广播更新,说明连接已关闭.似乎有很多次BluetootGatt在断开状态时不会响应状态变化.我关闭BluetoothGatt的方法是这样的.我让方法打开,以便Activity调用服务并断开连接,如果一台机器没有响应并且没有调用断开连接状态.
public void disconnectGatt(BluetoothGatt gatt) {
if(gatt != null) {
gatt.close();
gatt = null;
}
broadcastUpdate(ACTION_STATE_CLOSED);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27867 次 |
最近记录: |