Which Android API issues Scan Request and Responses

1.1k views Asked by At

Is it Android gatt connect or Android scan(getBluetoothLeScanner) which results in the Scan Request and Response? If we know the BLE Device address , can we directly connect it to without discovering the service?

1

There are 1 answers

6
Duy Kyou On

In Android BLE scan, the result for scan request will return in the way you want, for example

List<ScanFilter> filters = new ArrayList<ScanFilter>();

ScanFilter filter = new ScanFilter.Builder()
        .setServiceUuid(uuid)
        .setDeviceAddress(address)
        .setDeviceName(name)
        .build();
filters.add(filter);

And scan response will return at

onScanResult(int callbackType, ScanResult result)

ScanCallBack mCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            if (result != null){
                BluetoothDevice device = result.getDevice();
                mDeviceList.add(device);
                removeDuplicateWithOrder(mDeviceList);
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e("TAG", "Scan failed " + errorCode);
        }
    };

If we know the BLE Device address , can we directly connect it to without discovering the service?

The answer is YES and you can follow this example

public boolean connect(final String address) {
    if (mBluetoothAdapter == null || address == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return false;
    }

    // Previously connected device.  Try to reconnect.
    if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
            && mBluetoothGatt != null) {
        Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
        if (mBluetoothGatt.connect()) {
            return true;
        } else {
            return false;
        }
    }

    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        Log.w(TAG, "Device not found.  Unable to connect.");
        return false;
    }
    // We want to directly connect to the device, so we are setting the autoConnect
    // parameter to false.
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    Log.d(TAG, "Trying to create a new connection.");
    mBluetoothDeviceAddress = address;
    return true;
}

Hope this can help.