一、需求场景
在特定页面中开启车机蓝牙,手机端会弹出配对对话框,但车机端不弹出对话框,直接执行点击确定后的逻辑。
二、解决方案
需要在 Android 系统应用 Setting 中做相关的修改。修改源码文件位置为:AOSP/packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothPairingRequest.java文件
修改内容如下:
public final class BluetoothPairingRequest extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
return;
}
// convert broadcast intent into activity intent (same action string)
/*注释掉部分为之前的逻辑
//Intent pairingIntent = BluetoothPairingService.getPairingDialogIntent(context, intent);
//PowerManager powerManager =
// (PowerManager)context.getSystemService(Context.POWER_SERVICE);
//BluetoothDevice device =
// intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//String deviceAddress = device != null ? device.getAddress() : null;
//String deviceName = device != null ? device.getName() : null;
//boolean shouldShowDialog = LocalBluetoothPreferences.shouldShowDialogInForeground(
// context, deviceAddress, deviceName);
//if (powerManager.isInteractive() && shouldShowDialog) {
// Since the screen is on and the BT-related activity is in the foreground,
// just open the dialog
// context.startActivityAsUser(pairingIntent, UserHandle.CURRENT);
//} else {
// Put up a notification that leads to the dialog
// intent.setClass(context, BluetoothPairingService.class);
// context.startServiceAsUser(intent, UserHandle.CURRENT);
//}
}
}
之后在项目代码中注册广播 BluetoothDevice.ACTION_PAIRING_REQUEST 设置最大优先级
IntentFilter filter = new IntentFilter();
// 蓝牙自动连接
filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
filter.setPriority(10000);
mContext.registerReceiver(bluetoothReceiver, filter);
在广播接收器的 onReceive 方法中拦截广播
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String action = intent.getAction();
// 蓝牙自动连接
if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
abortBroadcast();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
device.setPairingConfirmation(true);
}
}
}
其中,abortBroadcast 方法能够拦截广播。 setPairingConfirmation(true) 为点击配对对话框的确定按键后执行的逻辑。在这里直接执行,即表示跳过对话框 直接点击确定按键的逻辑。但如果只是为了消除对话框,但不需要点击确认,该方法可以不用执行。