Android蓝牙配对框,根据输出log看到,包名是com.android.settings.bluetooth.BluetoothPairingDialog
是在Android原生Setting里面弹出的
对话框代码路径:packages\apps\Settings\src\com\android\settings\bluetooth\BluetoothPairingDialog.java
然后跟一下代码,找到触发这个配对框触发的地方: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);
}
}
}
由此想出处理方法:
自己定义一个BroadcastReceiver ,自动确认配对,然后拦截掉广播
java代码:
public final class BluetoothPairingRequestReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
return;
}
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
device.setPairingConfirmation(true);//确认配对
abortBroadcast();//拦截掉广播
} catch (Exception e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml:
<receiver android:name=".accessories.BluetoothPairingRequestReceiver " >
<intent-filter android:priority="1000"> //这里写成1000,最优先接收到广播
<action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
</intent-filter>
</receiver>
完毕