注册一个BluetoothDevice.ACTION_PAIRING_REQUEST
接收器 onCreate()
val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)
registerReceiver(pairingReceiver, pairingRequestFilter)
在接收器上设置您的密码setPin()
并拨打电话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()
}
}
}
}
不要忘记取消注册接收器onDestroy()
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(pairingReceiver)
}
如果它对您不起作用,请尝试将高优先级设置为接收器
val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)
pairingRequestFilter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY - 1
registerReceiver(pairingReceiver, pairingRequestFilter)
您还可以注册接收器BluetoothDevice.ACTION_BOND_STATE_CHANGED
以读取配对状态
val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
registerReceiver(receiver, filter)