Android车机系统-蓝牙自动连接,关闭蓝牙配对对话框解决方案

文章描述了如何在Android系统中修改Settings应用的源码以实现车机蓝牙配对时跳过对话框直接执行确认逻辑。通过修改BluetoothPairingRequest类和注册高优先级广播接收器,可以在手机端弹出配对请求时,车机端直接确认配对,无需用户交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、需求场景

在特定页面中开启车机蓝牙,手机端会弹出配对对话框,但车机端不弹出对话框,直接执行点击确定后的逻辑。

二、解决方案

需要在 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) 为点击配对对话框的确定按键后执行的逻辑。在这里直接执行,即表示跳过对话框 直接点击确定按键的逻辑。但如果只是为了消除对话框,但不需要点击确认,该方法可以不用执行。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

A-sL1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值