我正在尝试在没有用户交互的情况下配对蓝牙 (BLE) 设备 - 这意味着配对将仅以编程方式完成,用户不会选择蓝牙设备,也不会输入 PIN 码。我正在使用以下代码:
//request receiver
IntentFilter pairingRequestFilter = new
IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
pairingRequestFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
this.registerReceiver(mPairingRequestRecevier, pairingRequestFilter);
BluetoothManager bluetoothManager = (BluetoothManager)
this.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
BluetoothDevice mDevice = bluetoothAdapter.getRemoteDevice("macaddress");
mDevice.setPairingConfirmation(true);
mDevice.setPin("1234".getBytes());
mDevice.createBond();
private final BroadcastReceiver mPairingRequestRecevier = new
BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals
(intent.getAction()))
{
final BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int type =
intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
BluetoothDevice.ERROR);
if (type == BluetoothDevice.PAIRING_VARIANT_PIN)
{
device.setPin("1234".getBytes());
abortBroadcast();
}
else
{
}
}
}
};
<!-- permissions -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
发生了几件事:
- 该应用程序尝试配对设备,但我收到一条 toast 消息 - “无法配对设备,请稍后再试”。
- BroadcastReceiver 没有被调用。
有人可以帮我解决这个问题吗?