Android自动配对(绑定)蓝牙(BLE)设备,带有密码

时间:2017-12-06 12:12:12

标签: android bluetooth-lowenergy android-bluetooth pairing

我试图在没有用户交互的情况下配对蓝牙(BLE)设备 - 意味着配对只能以编程方式完成,用户不会选择蓝牙设备,也不会输入密码。 我使用以下代码:

//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" />

发生的事情很少:

  1. 该应用尝试配对该设备,但我收到了一个祝酒消息 - &#34;无法配对该设备,请稍后重试&#34;。
  2. BroadcastReceiver没有被调用。
  3. 有人可以帮我解决这个问题吗?

0 个答案:

没有答案