CompanionDeviceManager without using an intent chooser and scanning

506 Views Asked by At

I already have mac addresses of the Bluetooth device that I need to connect to. I do not wish to ask for any location permission. when my app is launched I need to scan and connect to the Bluetooth device using the mac address that is specified. Companion Device pairing that has been introduced in the latest android version.. I do not wish to open a chooser and get the callback result in onActivityResult. If there is any other way I could route all the scanning done by the Companion Device.

deviceManager.associate(pairingRequest,
    object : CompanionDeviceManager.Callback() {
        // Called when a device is found. Launch the IntentSender so the user
        // can select the device they want to pair with.
        override fun onDeviceFound(chooserLauncher: IntentSender) {
            startIntentSenderForResult(chooserLauncher,
                SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0)
        }

        override fun onFailure(error: CharSequence?) {
            // Handle the failure.
        }
    }, null)

in the below code if there is any way I could use a different mechanism so that my scanning can happen and I get the result somewhere and it does not ask for a dialog box for the user to enter.

 startIntentSenderForResult(chooserLauncher,
                    SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0)

or is there any way to use bluetooth functionality without asking for location permission?

2

There are 2 best solutions below

0
gaggleweed On

If you already know the mac address there is no need to scan. You can use

BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress)
0
Stoffe On
val scanFilter = ScanFilter.Builder().setDeviceAddress(staticBtMac).build()
val ledeviceFilter: BluetoothLeDeviceFilter = BluetoothLeDeviceFilter.Builder()
    .setScanFilter(scanFilter)
    .build()

Before you create the pairingRequest above in AssociationRequest.Builder

You would

val pairingRequest: AssociationRequest = AssociationRequest.Builder()
    .addDeviceFilter(ledeviceFilter)
    .setSingleDevice(true)

This will not list devices but just a permission pop up dialog with ->

"Allow 'Appname' to access your 'BT ADV Device name'" [Allow] [Don't Allow] buttons. It looks slightly different depending on if its Pixel or Samsung or other phone but it comes down to simple yes/no.

There is also the ..setSelfManaged(true) But this involves far more complexity and even more interaction with the framework.

If you really want to get into it you can see the actual code at https://cs.android.com/