- 可以自定义蓝牙配对对话框,以便控制对话框的显示时间。可参考以下示例代码:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() == BluetoothDevice.BOND_BONDING) {
// 自定义配对对话框
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_bluetooth_pairing_dialog);
dialog.setTitle(R.string.bluetooth_pairing_title);
((TextView) dialog.findViewById(R.id.tvDescription)).setText(context.getString(R.string.bluetooth_pairing_text, device.getName()));
Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
// 设置5秒钟后自动隐藏对话框
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}, 5000);
}
- 如果不需要自定义对话框,可以通过反射来改变配对对话框的显示时间。可参考以下示例代码:
private void setPairingConfirmation(BluetoothDevice device, boolean confirm) throws Exception {
Method setPairingConfirmationMethod = device.getClass().getDeclaredMethod("setPairingConfirmation", boolean.class);
setPairingConfirmationMethod.invoke(device, confirm);
if (!confirm) {
Method cancelPairingUserInputMethod = device.getClass().getDeclaredMethod("cancelPairingUserInput");
cancelPairingUserInputMethod.invoke(device);
}
}
private void pairDevice(BluetoothDevice device) {
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
try {
setPairingConfirmation(device, true);
device.createBond();
// 反射设置配对对话框显示时间为10秒
int timeout = 10000;
Field field = device.getClass().getField("TRANSACTION_PAIRING_WAIT");
int TRANSACTION