diff --git a/android/src/main/java/com/rusel/RCTBluetoothSerial/RCTBluetoothSerialModule.java b/android/src/main/java/com/rusel/RCTBluetoothSerial/RCTBluetoothSerialModule.java index aac796a..6fefe0a 100644 --- a/android/src/main/java/com/rusel/RCTBluetoothSerial/RCTBluetoothSerialModule.java +++ b/android/src/main/java/com/rusel/RCTBluetoothSerial/RCTBluetoothSerialModule.java @@ -44,6 +44,7 @@ public class RCTBluetoothSerialModule extends ReactContextBaseJavaModule impleme private static final String ERROR = "error"; private static final String FILE_PERCENT_LOADED = "filePercentLoaded"; private static final String FILE_LOADED = "fileLoaded"; + private static final String PAIRING_FAILED = "pairingFailed"; // Other stuff private static final int REQUEST_ENABLE_BLUETOOTH = 1; @@ -91,6 +92,7 @@ public RCTBluetoothSerialModule(ReactApplicationContext reactContext) { mReactContext.addActivityEventListener(this); mReactContext.addLifecycleEventListener(this); registerBluetoothStateReceiver(); + registerBondStateReceiver(); } @Override @@ -570,6 +572,11 @@ void onError (Exception e) { sendEvent(ERROR, params); } + void onPairingFailed() { + Log.d("BT", "PAIRING FAILED"); + sendEvent(PAIRING_FAILED, null); + } + void onFileChunkLoaded(double percentLoaded) { WritableMap params = Arguments.createMap(); @@ -654,6 +661,7 @@ private void pairDevice(BluetoothDevice device) { mPairDevicePromise.reject(e); mPairDevicePromise = null; } + onPairingFailed(); onError(e); } } @@ -668,6 +676,7 @@ private void unpairDevice(BluetoothDevice device) { Method m = device.getClass().getMethod("removeBond", (Class[]) null); m.invoke(device, (Object[]) null); registerDevicePairingReceiver(device.getAddress(), BluetoothDevice.BOND_NONE); + onPairingFailed(); } catch (Exception e) { Log.e(TAG, "Cannot unpair device", e); if (mPairDevicePromise != null) { @@ -721,7 +730,6 @@ public void onReceive(Context context, Intent intent) { onError(e); } } - } } }; @@ -799,4 +807,31 @@ public void onReceive(Context context, Intent intent) { mReactContext.registerReceiver(bluetoothStateReceiver, intentFilter); } -} \ No newline at end of file + + /** + * Register receiver for bond state change + */ + private void registerBondStateReceiver() { + IntentFilter intentFilter = new IntentFilter(); + + intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); + + final BroadcastReceiver bondStateReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + final String action = intent.getAction(); + if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { + final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); + switch (state) { + case BluetoothDevice.BOND_NONE: + if (D) Log.d(TAG, "Unsuccessful device pairing"); + sendEvent(PAIRING_FAILED, null); + break; + } + } + } + }; + + mReactContext.registerReceiver(bondStateReceiver, intentFilter); + } +}