[BT][Setting]如何在Framework层实现BT的自动配对

发布时间 2023-09-13 18:05:05作者: petercao

https://blog.csdn.net/weixin_44343246/article/details/109768335

[DESCRIPTION]

 客户有需求在没有屏和TP的情况下,如果有其他蓝牙对此设备进行配对,希望能自动完成配对动作,而不需要弹出需要用户确认的对话框。
  • 1

Android手机平台上当对方发起配对时主要使用种配对方式:

1.SSP数字比对,即双方手机产生配对密钥,由用户选择yes or no来进行鉴权连接。
2.Pin Code, 如果对方蓝牙不支持BT2.1以上版本,一般会走此流程,即双方输入四位数字进行配对。此方式需要预置4为数字,当对方发起配对时,需要输入此四位数字。
  • 1
  • 2

下面的内容是如何添加代码来实现BT自动配对的流程!

修改文件: (alps\packages\apps\settings\src\com\android\settings\bluetooth\BluetoothPairingRequest.java)
总共修改5处。

1.import android.util.Log;

2.在BluetoothPairingRequest类中定义两个变量
private static int mType = 0;
private BluetoothDevice mDevice;

3.在BluetoothPairingRequest 类中添加私有方法
private void autoPair(int value) {
switch (mType) {
case BluetoothDevice.PAIRING_VARIANT_PIN:
byte[] pin= {0,1,2,3};
mDevice.setPin(pin);
break;
case BluetoothDevice.PAIRING_VARIANT_PASSKEY:
mDevice.setPasskey(value);
break;
case BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION:
case BluetoothDevice.PAIRING_VARIANT_CONSENT:
mDevice.setPairingConfirmation(true);
break;
case BluetoothDevice.PAIRING_VARIANT_DISPLAY_PASSKEY:
case BluetoothDevice.PAIRING_VARIANT_DISPLAY_PIN:
// Do nothing.
break;
case BluetoothDevice.PAIRING_VARIANT_OOB_CONSENT:
mDevice.setRemoteOutOfBandData();
break;
default:
Log.e(“autoPair”, “Incorrect pairing type received”);
}
}
4. 在 int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
BluetoothDevice.ERROR);
后面添加以下两句
mType = type;
mDevice = device;
5. 注释掉context.startActivity(pairingIntent);这句,
并在 if (powerManager.isScreenOn() &&前面添加
int pairingKey = intent.getIntExtra (BluetoothDevice.EXTRA_PAIRING_KEY,
BluetoothDevice.ERROR);
autoPair(pairingKey);