如果有其他蓝牙设备申请对此设备进行连接,不需要弹出需要用户确认的对话框和pin code对话框,实现自动连接的一种实现方法;
修改设置蓝牙配对相关源码packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothPairingRequest.java 添加代码实现自动配对的过程:
添加变量
private static final int NOTIFICATION_ID = android.R.drawable.stat_sys_data_bluetooth;
private static int mType = 0; //feathure add
private BluetoothDevice mDevice; // feathure add
对变量赋值
// convert broadcast intent into activity intent (same action string)
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
BluetoothDevice.ERROR);
mType = type; //feathure add
mDevice = device; //feathure add
修改源代码pin code弹窗配对实现自动配对逻辑
int pairingKey = intent.getIntExtra (BluetoothDevice.EXTRA_PAIRING_KEY,
BluetoothDevice.ERROR); //feathure add
autoPair(pairingKey); //feathure add
if (powerManager.isInteractive() && shouldShowDialog) {
// Since the screen is on and the BT-related activity is in the foreground,
// just open the dialog
// context.startActivity(pairingIntent); //feathure comment out
添加自动配对的实现方法autoPair()
//feathure add start
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:
android.util.Log.e("autoPair", "Incorrect pairing type received");
}
} // feathure add end
以上代码修改基于android N平台Setting 源码,其他平台BT 配对逻辑类似可以参照修改验证,