android.bluetooth.BluetoothGatt#close ( )源码实例Demo

下面列出了android.bluetooth.BluetoothGatt#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: JayPS-AndroidApp   文件: Ble.java
public void disconnectAllDevices() {
    if (mBluetoothAdapter == null) {
        Log.w(TAG, "disconnectAllDevices BluetoothAdapter not initialized");
        return;
    }
    Log.d(TAG, "disconnectAllDevices mGatts.size:" + mGatts.size());
    Iterator<Map.Entry<String, BluetoothGatt>> iterator = mGatts.entrySet().iterator();
    while (iterator.hasNext()) {
        BluetoothGatt gatt = iterator.next().getValue();
        Log.d(TAG, "disconnect" + display(gatt));
        if (gatt != null) {
            gatt.disconnect();
            gatt.close();
            //gatt = null;
        }
    }
    mGatts.clear();
    if (connectionThread != null) {
        connectionThread.interrupt();
        connectionThread = null;
    }
}
 
源代码2 项目: bitgatt   文件: CloseGattTransaction.java
@Override
protected void transaction(GattTransactionCallback callback) {
    super.transaction(callback);
    getConnection().setState(GattState.CLOSING_GATT_CLIENT);
    BluetoothGatt localGatt = getConnection().getGatt();
    if(localGatt != null) {
        try {
            localGatt.close();
            getConnection().justClearGatt();
        } catch (NullPointerException e) {
            Timber.w(e, "[%s] If the underlying connection is gone, on some platforms, this can throw an NPE", getConnection().getDevice());
        }
    }
    getConnection().setState(GattState.CLOSE_GATT_CLIENT_SUCCESS);
    TransactionResult.Builder builder = new TransactionResult.Builder().transactionName(getName());
    builder.resultStatus(TransactionResult.TransactionResultStatus.SUCCESS);
    builder.gattState(getConnection().getGattState());
    mainThreadHandler.post(() -> {
        callCallbackWithTransactionResultAndRelease(callback, builder.build());
        getConnection().setState(GattState.DISCONNECTED);
    });
}
 
/**
 * CLEANS USER INTERFACE AND FINISH ACTIVITY
 *********************************************************/
public void exit(BluetoothGatt gatt) {
    gatt.close();
    if (service.getConnectedGatt() != null) {
        service.getConnectedGatt().close();
    }
    service.clearCache();
    bluetoothBinding.unbind();
    disconnect_gatt = false;
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            bluetoothGatt = null;
            service = null;
            bluetoothBinding = null;
            if (loadingdialog != null && loadingdialog.isShowing()) loadingdialog.dismiss();
            if (otaProgress != null && otaProgress.isShowing()) otaProgress.dismiss();
            if (otaSetup != null && otaSetup.isShowing()) otaSetup.dismiss();
            finish();
        }
    }, 1000);
}
 
源代码4 项目: science-journal   文件: MyBleService.java
public void disconnectDevice(String address) {
  BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
  if (btAdapter == null || address == null || bluetoothGatt == null) {
    // Broadcast the disconnect so BleFlow doesn't hang waiting for it; something else
    // already disconnected us in this case.
    sendGattBroadcast(address, BleEvents.GATT_DISCONNECT, null);
    return;
  }
  BluetoothDevice device = btAdapter.getRemoteDevice(address);
  int bleState = bluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
  if (bleState != BluetoothProfile.STATE_DISCONNECTED
      && bleState != BluetoothProfile.STATE_DISCONNECTING) {
    bluetoothGatt.disconnect();
  } else {
    bluetoothGatt.close();
    addressToGattClient.remove(address);
    sendGattBroadcast(address, BleEvents.GATT_DISCONNECT, null);
  }
}
 
源代码5 项目: bitgatt   文件: GattConnection.java
private void closeClientIf(BluetoothGatt localGatt) {
    try {
        localGatt.close();
    } catch (NullPointerException e) {
        // if we end up with an NPE here, it means that the underlying driver
        // didn't find the connection, this can happen with an unexpected
        // disconnection from the peripheral side which hasn't yet been realized
        // by the Android OS
        Timber.e(e, "[%s] Ran into OS Stack NPE", getDevice());
    }
}
 
源代码6 项目: Android-BLE   文件: BleRequestImpl.java
/**
 * 清除蓝牙蓝牙连接设备的指定蓝牙地址
 *
 * @param address 蓝牙地址
 */
public void close(String address) {
    BluetoothGatt gatt = gattHashMap.get(address);
    if (gatt != null) {
        gatt.close();
        gattHashMap.remove(address);
    }
    connectedAddressList.remove(address);
}
 
源代码7 项目: flutter-plugins   文件: ESenseManager.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        gatt.close();
        mCharacteristicMap.clear();
        if(mConnectionListener != null) {
            mConnectionListener.onDisconnected(ESenseManager.this);
        }
    }

}
 
源代码8 项目: GizwitsBLE   文件: AndroidBle.java
@Override
public void disconnect(String address) {
	if (mBluetoothGatts.containsKey(address)) {
		BluetoothGatt gatt = mBluetoothGatts.remove(address);
		if (gatt != null) {
			gatt.disconnect();
			gatt.close();
		}
	}
}
 
源代码9 项目: bleTester   文件: BleService.java
@SuppressLint("NewApi")
public void close(BluetoothGatt gatt) {
	gatt.disconnect();
	gatt.close();
	if (mBluetoothAdapter != null) {
		mBluetoothAdapter.cancelDiscovery();
		mBluetoothAdapter = null;
	}
}
 
源代码10 项目: microbit   文件: DfuBaseService.java
/**
 * Closes the GATT device and cleans up.
 *
 * @param gatt the GATT device to be closed
 */
private void close(final BluetoothGatt gatt) {
    logi("Cleaning up...");
    sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.close()");
    gatt.disconnect();
    gatt.close();
    mConnectionState = STATE_CLOSED;
}
 
/**
 * close bluetooth, release resource
 * @param address
 */
public boolean close(String address) {
    if (!isEmpty(address) && gattMap.containsKey(address)){
        Logger.w("close gatt server " + address);
        BluetoothGatt mBluetoothGatt = gattMap.get(address);
        mBluetoothGatt.close();
        gattMap.remove(address);
        updateConnectStateListener(address, ConnectState.NORMAL);
        return true;
    }
    return false;
}
 
源代码12 项目: thunderboard-android   文件: GattManager.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    BluetoothDevice device = gatt.getDevice();

    Timber.d("device: %s, status: %d, newState: %d", (device != null), status, newState);

    if (BluetoothGatt.GATT_SUCCESS != status) {
        gatt.disconnect();
        return;
    }

    if (BluetoothProfile.STATE_DISCONNECTED == newState) {
        gatt.close();
    } else if (BluetoothProfile.STATE_CONNECTED == newState) {
        gatt.discoverServices();
        preferenceManager.addConnected(device.getAddress(), device.getName());
    }

    ThunderBoardDevice bgd = bleManager.getDeviceFromCache(device.getAddress());
    if (bgd != null) {
        bgd.setState(newState);
        bleManager.selectedDeviceMonitor.onNext(bgd);
        bleManager.selectedDeviceStatusMonitor.onNext(new StatusEvent(bgd));
    }
}
 
源代码13 项目: science-journal   文件: MyBleService.java
public boolean connect(String address) {
  if (btAdapter == null) {
    // Not sure how we could get here, but it happens (b/36738130), so flag an error
    // instead of crashing.
    return false;
  }
  BluetoothDevice device = btAdapter.getRemoteDevice(address);
  //  Explicitly check if Ble is enabled, otherwise it attempts a connection
  //  that never timesout even though it should.
  if (device == null || !isBleEnabled()) {
    return false;
  }
  BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
  int connectionState = bluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
  if (bluetoothGatt != null && connectionState != BluetoothProfile.STATE_CONNECTED) {
    return bluetoothGatt.connect();
  }
  if (bluetoothGatt != null && connectionState == BluetoothProfile.STATE_CONNECTED) {
    sendGattBroadcast(address, BleEvents.GATT_CONNECT, null);
    return true;
  }

  if (bluetoothGatt != null) {
    bluetoothGatt.close();
  }
  bluetoothGatt =
      device.connectGatt(
          this,
          false, // autoConnect = false
          gattCallbacks);
  addressToGattClient.put(address, bluetoothGatt);
  return true;
}
 
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                    int newState) {
    Log.i(TAG, "BLE connection state changed: " + status + "; new state: "
            + AmazonFreeRTOSConstants.BleConnectionState.values()[newState]);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            int bondState = mBluetoothDevice.getBondState();

            mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_CONNECTED;
            Log.i(TAG, "Connected to GATT server.");
            // If the device is already bonded or will not bond we can call discoverServices() immediately
            if (bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.BOND_BONDED) {
                discoverServices();
            }
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_DISCONNECTED;
            Log.i(TAG, "Disconnected from GATT server.");

            // If ble connection is closed, there's no need to keep mqtt connection open.
            if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected) {
                disconnectFromIot();
            }

            // If not using auto reconnect or if user initiated disconnect
            if (!mGattAutoReconnect) {
                gatt.close();
                mBluetoothGatt = null;
            }
            cleanUp();
        }
    } else {
        Log.i(TAG, "Disconnected from GATT server due to error ot peripheral initiated disconnect.");

        mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_DISCONNECTED;

        if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected) {
            disconnectFromIot();
        }

        if (!mGattAutoReconnect) {
            gatt.close();
            mBluetoothGatt = null;
        }
        cleanUp();
    }
    mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
}
 
源代码15 项目: tap-android-sdk   文件: BluetoothManager.java
private void closeGatt(BluetoothGatt gatt) {
    removeExecutor(getExecutor(gatt));
    gatt.close();
}
 
源代码16 项目: android-ponewheel   文件: BluetoothUtilImpl.java
private void onOWStateChangedToDisconnected(BluetoothGatt gatt, Context context) {
    //TODO: we really should have a BluetoothService we kill and restart
    Timber.i("We got disconnected from our Device: " + gatt.getDevice().getAddress());
    if (Looper.myLooper() == null) {
        Looper.prepare();
    }
    Toast.makeText(mainActivity, "We got disconnected from our device: " + gatt.getDevice().getAddress(), Toast.LENGTH_SHORT).show();

    mainActivity.deviceConnectedTimer(false);
    mOWDevice.isConnected.set(false);
    App.INSTANCE.releaseWakeLock();
    mScanResults.clear();

    if (App.INSTANCE.getSharedPreferences().shouldAutoReconnect()) {
        mRetryCount++;
        Timber.i("mRetryCount=" + mRetryCount);

        try {
            if (mRetryCount == 20) {
                Timber.i("Reached too many retries, stopping search");
                gatt.close();
                stopScanning();
                disconnect();
                //mainActivity.invalidateOptionsMenu();
            } else {
                Timber.i("Waiting for 5 seconds until trying to connect to OW again.");
                TimeUnit.SECONDS.sleep(5);
                Timber.i("Trying to connect to OW at " + mOWDevice.deviceMacAddress.get());
                //BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mOWDevice.deviceMacAddress.get());
                //connectToDevice(device);
                gatt.connect();
            }
        } catch (InterruptedException e) {
            Timber.d("Connection to OW got interrupted:" + e.getMessage());
        }
    } else {
        gatt.close();
        mainActivity.invalidateOptionsMenu();
    }

}
 
源代码17 项目: EFRConnect-android   文件: BlueToothService.java
private void clearGatt(BluetoothGatt bluetoothGatt) {
    bluetoothGatt.disconnect();
    bluetoothGatt.close();
}
 
源代码18 项目: RxAndroidBle   文件: BleConnectionCompat.java
public BluetoothGatt connectGatt(BluetoothDevice remoteDevice, boolean autoConnect, BluetoothGattCallback bluetoothGattCallback) {

        if (remoteDevice == null) {
            return null;
        }

        /**
         * Issue that caused a race condition mentioned below was fixed in 7.0.0_r1
         * https://android.googlesource.com/platform/frameworks/base/+/android-7.0.0_r1/core/java/android/bluetooth/BluetoothGatt.java#649
         * compared to
         * https://android.googlesource.com/platform/frameworks/base/+/android-6.0.1_r72/core/java/android/bluetooth/BluetoothGatt.java#739
         * issue: https://android.googlesource.com/platform/frameworks/base/+/d35167adcaa40cb54df8e392379dfdfe98bcdba2%5E%21/#F0
          */
        if (Build.VERSION.SDK_INT >= 24 /* Build.VERSION_CODES.N */ || !autoConnect) {
            return connectGattCompat(bluetoothGattCallback, remoteDevice, autoConnect);
        }

        /**
         * Some implementations of Bluetooth Stack have a race condition where autoConnect flag
         * is not properly set before calling connectGatt. That's the reason for using reflection
         * to set the flag manually.
         */

        try {
            RxBleLog.v("Trying to connectGatt using reflection.");
            Object iBluetoothGatt = getIBluetoothGatt(getIBluetoothManager());

            if (iBluetoothGatt == null) {
                RxBleLog.w("Couldn't get iBluetoothGatt object");
                return connectGattCompat(bluetoothGattCallback, remoteDevice, true);
            }

            BluetoothGatt bluetoothGatt = createBluetoothGatt(iBluetoothGatt, remoteDevice);

            if (bluetoothGatt == null) {
                RxBleLog.w("Couldn't create BluetoothGatt object");
                return connectGattCompat(bluetoothGattCallback, remoteDevice, true);
            }

            boolean connectedSuccessfully = connectUsingReflection(bluetoothGatt, bluetoothGattCallback, true);

            if (!connectedSuccessfully) {
                RxBleLog.w("Connection using reflection failed, closing gatt");
                bluetoothGatt.close();
            }

            return bluetoothGatt;
        } catch (NoSuchMethodException
                | IllegalAccessException
                | IllegalArgumentException
                | InvocationTargetException
                | InstantiationException
                | NoSuchFieldException exception) {
            RxBleLog.w(exception, "Error while trying to connect via reflection");
            return connectGattCompat(bluetoothGattCallback, remoteDevice, true);
        }
    }
 
源代码19 项目: science-journal   文件: MyBleService.java
void resetGatt() {
  for (BluetoothGatt bluetoothGatt : addressToGattClient.values()) {
    bluetoothGatt.close();
  }
}
 
源代码20 项目: bean-sdk-android   文件: TestBeanBLE.java
@Suppress
public void testBLE() throws InterruptedException {

    // Scan/Discover
    BluetoothDevice device = findDevice();

    // Connect to closest device (hopefully a Bean)
    BluetoothGatt gatt = connectGatt(device);

    // Clear Android Cache
    refreshDeviceCache(gatt);

    // Discover services
    discoverServices(gatt);

    // Read HW version from Device Info Service
    readHardwareVersion(gatt);

    // Enable notifications on OAD Identify char
    enableNotificationOADIdentify(gatt);

    // Write 0x0000 to OAD Identify char
    writeCharacteristicOADIdentify(gatt);

    // Receive notification
    receiveNotificationOADIdentify();

    gatt.disconnect();
    gatt.close();

}