我正在将打印数据写入Zebra ZD410打印机的BluetoothGattCharacteristic
。我通过将数据分块为20个字节的块并使用以下代码一次写入一个块来实现此目的:
mCharacteristic.setValue(bytes);
boolean status = mGatt.writeCharacteristic(mCharacteristic);
然后等到我开始写下一个块之前收到BluetoothGattCallback.onCharacteristicWrite()
。这很好用。
如果我disconnect()
和close()
BluetoothGatt
以后再次使用BluetoothDevice.connectGatt()
连接到同一设备,然后尝试在Characteristic
之后写{ {1}}已被调用,我再次拥有onServicesDiscovered()
,写入将失败。我的意思是,当我现在写Characteristic
时,Characteristic
会被onCharacteristicWrite()
调用,Characteristic
会getValue()
返回最后一个值写在老加特身上。
在尝试解决这两天并阅读大量SO帖后,我还没有找到解决方案。
我该如何解决这个问题?
修改
以下是BluetoothGattCallback
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback()
{
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
FALog.i(TAG, "onConnectionStateChange Status: " + status);
switch (newState)
{
case BluetoothProfile.STATE_CONNECTED:
FALog.i(TAG, "gattCallback STATE_CONNECTED");
gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
disconnectAndCloseGatt();
mCharacteristic = null;
connectionFailed();
FALog.e(TAG, "gattCallback STATE_DISCONNECTED");
break;
default:
FALog.e(TAG, "gattCallback STATE_OTHER");
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{
BluetoothGattService service = gatt.getService(PRINTER_SERVICE_UUID);
if (service != null)
{
BluetoothGattCharacteristic characteristic = service.getCharacteristic
(PRINTER_SERVICE_CHARACTERISTIC_UUID);
if (characteristic != null)
{
mCharacteristic = characteristic;
mInternalState = STATE_CONNECTED;
mState = State.CONNECTED;
notifyStateChanged();
print("~JA");
FALog.d(TAG, "Printer connected");
mBluetoothActivity.runOnUiThread(new Runnable()
{
@Override
public void run()
{
mListener.onPrinterConnected();
}
});
}
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
FALog.d(TAG, "received onCharacteristicWrite " + new String(characteristic.getValue()) + "; success: " +
(status == BluetoothGatt.GATT_SUCCESS));
if (status == BluetoothGatt.GATT_SUCCESS)
{
handler.removeCallbacks(writeRunnable);
popQueueAndReleaseLock();
}
}
};