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

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

@Override
public void applyStrategy() {
    Timber.d("Applying tracker vanishing while in gatt operation strategy");
    if(connection != null) {
        connection.setState(GattState.DISCONNECTING);
        BluetoothGatt localGatt = connection.getGatt();
        if(localGatt != null) {
            localGatt.disconnect();
        } else {
            Timber.d("Could not apply strategy because the gatt was null");
        }
    }
    // we might not get the gatt disconnect callback if the if is lost,
    // so in this scenario we will have to wait for the client_if to dump for sure,
    // at least 1s on pixel
    Timber.v("Waiting %dms for the client_if to dump", WAIT_TIME_FOR_DISCONNECTION);
    if(connection != null) {
        connection.getMainHandler().postDelayed(() -> {
            connection.setState(GattState.DISCONNECTED);
            if (FitbitGatt.getInstance().getServer() != null) {
                FitbitGatt.getInstance().getServer().setState(GattState.DISCONNECTED);
            }
            Timber.v("Strategy is done, gatt can be used again");
        }, WAIT_TIME_FOR_DISCONNECTION);
    }
}
 
源代码2 项目: neatle   文件: Device.java
@Override
public void disconnect() {
    NeatleLogger.i("Disconnecting");
    stopDiscovery();
    BluetoothGatt target;
    int oldState;

    synchronized (lock) {
        target = gatt;
        gatt = null;
        this.serviceDiscovered = false;
        oldState = state;
        state = BluetoothGatt.STATE_DISCONNECTED;
    }
    if (target != null) {
        target.disconnect();
    }
    notifyConnectionStateChange(oldState, BluetoothGatt.STATE_DISCONNECTED);
}
 
源代码3 项目: 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;
    }
}
 
源代码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 项目: Mi-Band   文件: BTConnectionManager.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    //Log.e(TAG, "onConnectionStateChange (2): " + newState);

    BTConnectionManager.this.gatt = gatt;

    if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
        gatt.discoverServices();
    } else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED) {
        //Log.e(TAG, "onConnectionStateChange disconnect: " + newState);
        //toggleNotifications(false);
        //disconnect();
    } else if (status != BluetoothGatt.GATT_SUCCESS) {
        gatt.disconnect();
    }
}
 
源代码6 项目: bitgatt   文件: GattConnection.java
/**
 * Will unregister this process from the system so no further callback will be delivered, note
 * this does not actually disconnect the remote peripheral
 */

public void disconnect() {
    if (mockMode) {
        mockDisconnect();
        return;
    }
    BluetoothGatt localGatt = gatt;
    if (localGatt == null) {
        setState(GattState.DISCONNECTED);
    } else {
        /*
         * It is important to note that after disconnect is processed, there can be a long
         * supervision timeout if the device disconnects itself, the state will remain
         * {@link GattState.DISCONNECTING} until that is complete ...
         */
        try {
            localGatt.disconnect();
        } catch (NullPointerException e) {
            // this means that the hardware's underlying connection went away while
            // we were trying to cancel a connection attempt
            // there are a number of phones that have this flaw, we don't need to do
            // anything though, if this NPEs it means that the connection is already
            // cancelled ... there is nothing there to cancel
            Timber.e(e, "[%s] OS Stack Failure while disconnecting", getDevice());
        }
        setState(GattState.DISCONNECTING);
    }
}
 
源代码7 项目: AndroidBleManager   文件: ConnectRequestQueue.java
/**
 * 断开蓝牙连接,不会释放BluetoothGatt持有的所有资源,可以调用mBluetoothGatt.connect()很快重新连接上
 * 如果不及时释放资源,可能出现133错误,http://www.loverobots.cn/android-ble-connection-solution-bluetoothgatt-status-133.html
 * @param address
 */
public void disconnect(String address){
    if (!isEmpty(address) && gattMap.containsKey(address)){
        Logger.w("disconnect gatt server " + address);
        BluetoothGatt mBluetoothGatt = gattMap.get(address);
        mBluetoothGatt.disconnect();
        updateConnectState(address, ConnectState.NORMAL);
    }
}
 
源代码8 项目: itag   文件: BLEPeripheralDefault.java
@Override
public void disconnect() {
    if (BLEPeripheralState.disconnected.equals(state)) {
        if (BuildConfig.DEBUG) {
            Log.d(LT, "disconnect id=" + identifier() + ", already disconnected, no action");
        }
    } else {
        BluetoothGatt gatt = gatt();
        boolean connected = isConnected();
        if (connected && gatt!=null) {
            if (BuildConfig.DEBUG) {
                Log.d(LT, "disconnect id=" + identifier() + ", connected, will wait connection change");
            }
            setState(BLEPeripheralState.disconnecting);
            gatt.disconnect();
        } else {
            if (BuildConfig.DEBUG) {
                Log.d(LT, "disconnect id=" + identifier() + ", not connected will simulate connection change");
            }
            setState(BLEPeripheralState.disconnecting);
            if (gatt != null)
                    gatt.disconnect(); // just in case ?
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            close();
            observables.channelDisconnected.broadcast(new BLEPeripheralObservablesInterface.DisconnectedEvent(0));
        }
    }
}
 
源代码9 项目: bleTester   文件: BleService.java
@SuppressLint("NewApi")
public void close(BluetoothGatt gatt) {
	gatt.disconnect();
	gatt.close();
	if (mBluetoothAdapter != null) {
		mBluetoothAdapter.cancelDiscovery();
		mBluetoothAdapter = null;
	}
}
 
源代码10 项目: EFRConnect-android   文件: LightActivity.java
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        BluetoothGatt gatt = service.getConnectedGatt();
        gatt.disconnect();
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
 
/**
 * 断开蓝牙连接,不会释放BluetoothGatt持有的所有资源,可以调用mBluetoothGatt.connect()很快重新连接上
 * 如果不及时释放资源,可能出现133错误,http://www.loverobots.cn/android-ble-connection-solution-bluetoothgatt-status-133.html
 * @param address
 */
public void disconnect(String address){
    if (!isEmpty(address) && gattMap.containsKey(address)){
        reconnectParamsBean = new ReconnectParamsBean(address);
        reconnectParamsBean.setNumber(1000);
        Logger.w("disconnect gatt server " + address);
        BluetoothGatt mBluetoothGatt = gattMap.get(address);
        mBluetoothGatt.disconnect();
        updateConnectStateListener(address, ConnectState.NORMAL);
    }
}
 
源代码12 项目: microbit   文件: DfuBaseService.java
/**
 * Disconnects from the device. This is SYNCHRONOUS method and waits until the callback returns new state. Terminates immediately if device is already disconnected. Do not call this method
 * directly, use {@link #terminateConnection(android.bluetooth.BluetoothGatt, int)} instead.
 *
 * @param gatt the GATT device that has to be disconnected
 */
private void disconnect(final BluetoothGatt gatt) {
    if (mConnectionState == STATE_DISCONNECTED)
        return;

    mConnectionState = STATE_DISCONNECTING;
    logi("Disconnecting from the device...");
    gatt.disconnect();

    // We have to wait until device gets disconnected or an error occur
    waitUntilDisconnected();
}
 
源代码13 项目: DeviceConnect-Android   文件: HeartRateConnector.java
/**
 * Disconnect to the bluetooth device.
 *
 * @param device bluetooth device
 */
public void disconnectDevice(final BluetoothDevice device) {
    if (device == null) {
        throw new IllegalArgumentException("device is null");
    }
    String address = device.getAddress();
    synchronized (mHRDevices) {
        for (BluetoothGatt gatt : mHRDevices.keySet()) {
            if (gatt.getDevice().getAddress().equalsIgnoreCase(address)) {
                gatt.disconnect();
            }
        }
    }
    mRegisterDevices.remove(device.getAddress());
}
 
源代码14 项目: science-journal   文件: MkrSciBleManager.java
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
  if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
    this.gatt = gatt;
    characteristics.clear();
    gatt.discoverServices();
  } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
    readyForAction = false;
    gatt.disconnect();
  }
}
 
源代码15 项目: xDrip   文件: G5CollectionService.java
private synchronized void doDisconnectMessage(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
       Log.d(TAG, "doDisconnectMessage() start");
       gatt.setCharacteristicNotification(controlCharacteristic, false);
       final DisconnectTxMessage disconnectTx = new DisconnectTxMessage();
       characteristic.setValue(disconnectTx.byteSequence);
       gatt.writeCharacteristic(characteristic);
       gatt.disconnect();
       Log.d(TAG, "doDisconnectMessage() finished");
}
 
源代码16 项目: xDrip-plus   文件: G5CollectionService.java
private synchronized void doDisconnectMessage(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
       Log.d(TAG, "doDisconnectMessage() start");
       gatt.setCharacteristicNotification(controlCharacteristic, false);
       final DisconnectTxMessage disconnectTx = new DisconnectTxMessage();
       characteristic.setValue(disconnectTx.byteSequence);
       gatt.writeCharacteristic(characteristic);
       gatt.disconnect();
       Log.d(TAG, "doDisconnectMessage() finished");
}
 
源代码17 项目: xDrip-plus   文件: G5CollectionService.java
private synchronized void doDisconnectMessage(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
       Log.d(TAG, "doDisconnectMessage() start");
       gatt.setCharacteristicNotification(controlCharacteristic, false);
       final DisconnectTxMessage disconnectTx = new DisconnectTxMessage();
       characteristic.setValue(disconnectTx.byteSequence);
       gatt.writeCharacteristic(characteristic);
       gatt.disconnect();
       Log.d(TAG, "doDisconnectMessage() finished");
}
 
源代码18 项目: Android-nRF-Beacon   文件: UpdateService.java
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
	if (status != BluetoothGatt.GATT_SUCCESS) {
		logw("Service discovery error: " + status);
		broadcastError(status);
		return;
	}

	// We have successfully connected
	setState(STATE_CONNECTED);

	// Search for config service
	final BluetoothGattService configService = gatt.getService(CONFIG_SERVICE_UUID);
	if (configService == null) {
		// Config service is not present
		broadcastError(ERROR_UNSUPPORTED_DEVICE);
		setState(STATE_DISCONNECTING);
		gatt.disconnect();
		return;
	}

	mUuidCharacteristic = configService.getCharacteristic(CONFIG_UUID_CHARACTERISTIC_UUID);
	mMajorMinorCharacteristic = configService.getCharacteristic(CONFIG_MAJOR_MINOR_CHARACTERISTIC_UUID);
	mRssiCharacteristic = configService.getCharacteristic(CONFIG_RSSI_CHARACTERISTIC_UUID);
	mManufacturerIdCharacteristic = configService.getCharacteristic(CONFIG_MANUFACTURER_ID_CHARACTERISTIC_UUID);
	mAdvIntervalCharacteristic = configService.getCharacteristic(CONFIG_ADV_INTERVAL_CHARACTERISTIC_UUID);
	mLedSettingsCharacteristic = configService.getCharacteristic(CONFIG_LED_SETTINGS_CHARACTERISTIC_UUID);

	if (mUuidCharacteristic != null || mMajorMinorCharacteristic != null || mRssiCharacteristic != null)
		broadcastOperationCompleted(mManufacturerIdCharacteristic != null || mAdvIntervalCharacteristic != null || mLedSettingsCharacteristic != null);

	if (mUuidCharacteristic == null && mMajorMinorCharacteristic == null && mRssiCharacteristic == null) {
		// Config characteristics is not present
		broadcastError(ERROR_UNSUPPORTED_DEVICE);
		setState(STATE_DISCONNECTING);
		gatt.disconnect();
	}
}
 
源代码19 项目: EFRConnect-android   文件: BlueToothService.java
private void clearGatt(BluetoothGatt bluetoothGatt) {
    bluetoothGatt.disconnect();
    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();

}