From e06677e883c4f5bb7921500afaf19e4b120e2e40 Mon Sep 17 00:00:00 2001 From: Aleksander Nowakowski Date: Wed, 5 Oct 2016 12:54:49 +0200 Subject: [PATCH] Bug fix: Closing gatt in synchronized block Otherwise the mBluetoothGatt.close() may throw NPE --- .../nrftoolbox/profile/BleManager.java | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleManager.java b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleManager.java index b4c2ed5c..91467fd1 100644 --- a/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleManager.java +++ b/app/src/main/java/no/nordicsemi/android/nrftoolbox/profile/BleManager.java @@ -80,6 +80,7 @@ public abstract class BleManager { private final static String ERROR_WRITE_DESCRIPTOR = "Error on writing descriptor"; private final static String ERROR_READ_CHARACTERISTIC = "Error on reading characteristic"; + private final Object mLock = new Object(); /** * The log session or null if nRF Logger is not installed. */ @@ -197,18 +198,20 @@ public abstract class BleManager { if (mConnected) return; - if (mBluetoothGatt != null) { - Logger.d(mLogSession, "gatt.close()"); - mBluetoothGatt.close(); - mBluetoothGatt = null; - } + synchronized (mLock) { + if (mBluetoothGatt != null) { + Logger.d(mLogSession, "gatt.close()"); + mBluetoothGatt.close(); + mBluetoothGatt = null; + } - final boolean autoConnect = shouldAutoConnect(); - mUserDisconnected = !autoConnect; // We will receive Linkloss events only when the device is connected with autoConnect=true - Logger.v(mLogSession, "Connecting..."); - Logger.d(mLogSession, "gatt = device.connectGatt(autoConnect = " + autoConnect + ")"); - mBluetoothDevice = device; - mBluetoothGatt = device.connectGatt(mContext, autoConnect, getGattCallback()); + final boolean autoConnect = shouldAutoConnect(); + mUserDisconnected = !autoConnect; // We will receive Linkloss events only when the device is connected with autoConnect=true + Logger.v(mLogSession, "Connecting..."); + Logger.d(mLogSession, "gatt = device.connectGatt(autoConnect = " + autoConnect + ")"); + mBluetoothDevice = device; + mBluetoothGatt = device.connectGatt(mContext, autoConnect, getGattCallback()); + } } /** @@ -245,13 +248,15 @@ public abstract class BleManager { } catch (Exception e) { // the receiver must have been not registered or unregistered before } - if (mBluetoothGatt != null) { - Logger.d(mLogSession, "gatt.close()"); - mBluetoothGatt.close(); - mBluetoothGatt = null; + synchronized (mLock) { + if (mBluetoothGatt != null) { + Logger.d(mLogSession, "gatt.close()"); + mBluetoothGatt.close(); + mBluetoothGatt = null; + } + mBluetoothDevice = null; + mUserDisconnected = false; } - mBluetoothDevice = null; - mUserDisconnected = false; } /**