From 9ffe09cb6e5acc28d468a5c0fdd79c472f6d70d9 Mon Sep 17 00:00:00 2001 From: Shelomoh <49126015+shelomohkhual@users.noreply.github.com> Date: Mon, 16 Sep 2024 15:44:36 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20Bluetooth=20connection=20failed:=20read?= =?UTF-8?q?=20failed,=20socket=20might=20closed=20or=E2=80=A6=20(#93)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: Bluetooth connection failed: read failed, socket might closed or timeout, read ret: -1 * add missing param and fix catch error * fix: java.string error --- .../printer/adapter/BLEPrinterAdapter.java | 35 ++++++++++++++----- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/android/src/main/java/com/pinmi/react/printer/adapter/BLEPrinterAdapter.java b/android/src/main/java/com/pinmi/react/printer/adapter/BLEPrinterAdapter.java index 3b5a22f..9d77969 100644 --- a/android/src/main/java/com/pinmi/react/printer/adapter/BLEPrinterAdapter.java +++ b/android/src/main/java/com/pinmi/react/printer/adapter/BLEPrinterAdapter.java @@ -128,13 +128,19 @@ public void selectDevice(PrinterDeviceId printerDeviceId, Callback successCallba if(device.getAddress().equals(blePrinterDeviceId.getInnerMacAddress())){ try{ - connectBluetoothDevice(device); + connectBluetoothDevice(device, false); successCallback.invoke(new BLEPrinterDevice(this.mBluetoothDevice).toRNWritableMap()); return; - }catch (IOException e){ - e.printStackTrace(); - errorCallback.invoke(e.getMessage()); - return; + } catch (IOException e) { + try { + connectBluetoothDevice(device, true); + successCallback.invoke(new BLEPrinterDevice(this.mBluetoothDevice).toRNWritableMap()); + return; + } catch (IOException er) { + er.printStackTrace(); + errorCallback.invoke(er.getMessage()); + return; + } } } } @@ -144,11 +150,22 @@ public void selectDevice(PrinterDeviceId printerDeviceId, Callback successCallba return; } - private void connectBluetoothDevice(BluetoothDevice device) throws IOException{ + private void connectBluetoothDevice(BluetoothDevice device, Boolean retry) throws IOException { UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); - this.mBluetoothSocket = device.createRfcommSocketToServiceRecord(uuid); - this.mBluetoothSocket.connect(); - this.mBluetoothDevice = device;//最后一步执行 + + if (retry) { + try { + this.mBluetoothSocket = (BluetoothSocket) device.getClass() + .getMethod("createRfcommSocket", new Class[] { int.class }).invoke(device, 1); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + this.mBluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid); + this.mBluetoothSocket.connect(); + } + + this.mBluetoothDevice = device;// 最后一步执行 }