@@ -982,14 +982,9 @@ private void bluetoothStateChangeHandler(int prevState, int newState) {
982982 sendBluetoothStateCallback (isUp );
983983
984984 //If Bluetooth is off, send service down event to proxy objects, and unbind
985- if (!isUp ) {
986- //Only unbind with mEnable flag not set
987- //For race condition: disable and enable back-to-back
988- //Avoid unbind right after enable due to callback from disable
989- if ((!mEnable ) && (mBluetooth != null )) {
990- sendBluetoothServiceDownCallback ();
991- unbindAndFinish ();
992- }
985+ if (!isUp && canUnbindBluetoothService ()) {
986+ sendBluetoothServiceDownCallback ();
987+ unbindAndFinish ();
993988 }
994989 }
995990
@@ -1037,4 +1032,22 @@ private boolean waitForOnOff(boolean on, boolean off) {
10371032 Log .e (TAG ,"waitForOnOff time out" );
10381033 return false ;
10391034 }
1035+
1036+ private boolean canUnbindBluetoothService () {
1037+ synchronized (mConnection ) {
1038+ //Only unbind with mEnable flag not set
1039+ //For race condition: disable and enable back-to-back
1040+ //Avoid unbind right after enable due to callback from disable
1041+ //Only unbind with Bluetooth at OFF state
1042+ //Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
1043+ try {
1044+ if (mEnable || (mBluetooth == null )) return false ;
1045+ if (mHandler .hasMessages (MESSAGE_BLUETOOTH_STATE_CHANGE )) return false ;
1046+ return (mBluetooth .getState () == BluetoothAdapter .STATE_OFF );
1047+ } catch (RemoteException e ) {
1048+ Log .e (TAG , "getState()" , e );
1049+ }
1050+ }
1051+ return false ;
1052+ }
10401053}
0 commit comments