How to pair Bluetooth device programmatically Android

前端 未结 8 1974
不知归路
不知归路 2020-11-27 12:35

I am developing an application where I want to connect a Bluetooth device main issue is I don\'t want user to enter required pin instead application should do that by himsel

8条回答
  •  孤城傲影
    2020-11-27 13:38

    Register a BluetoothDevice.ACTION_PAIRING_REQUEST receiver onCreate()

    val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)
            registerReceiver(pairingReceiver, pairingRequestFilter)
    

    on receiver set your pin using setPin() and call abortBroadcast()

    val PAIRING_PIN=1234
    
    private var pairingReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                val action = intent!!.action
                if (BluetoothDevice.ACTION_PAIRING_REQUEST == action) {
                    val device: BluetoothDevice? =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    val type =intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR)
                    if (type == BluetoothDevice.PAIRING_VARIANT_PIN) {
                        device?.setPin(PAIRING_PIN.toByteArray())
                        abortBroadcast()
                    }
                }
            }
        }
    

    Don't forget to unregister receiver on onDestroy()

    override fun onDestroy() {
            super.onDestroy()
            unregisterReceiver(pairingReceiver)
        }
    

    if it doesn't work for you, try setting hight priority to receiver

    val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)          
    pairingRequestFilter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY - 1
                registerReceiver(pairingReceiver, pairingRequestFilter)
    

    Also you can register a receiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED to read status of pairing

    val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
            registerReceiver(receiver, filter)
    

提交回复
热议问题