android设备和蓝牙耳机之间的编程连接

时间:2018-08-29 08:53:17

标签: android bluetooth android-bluetooth

我该如何在android中制作一个可以在android设备和蓝牙扬声器之间建立连接的应用程序。

1 个答案:

答案 0 :(得分:0)

如何配对:

   private void pairDevice(BluetoothDevice device) {
            try {
                Method method = device.getClass().getMethod("createBond", (Class[]) null);
                method.invoke(device, (Object[]) null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

如何取消配对:

 private void unpairDevice(BluetoothDevice device) {
            try {
                Method method = device.getClass().getMethod("removeBond", (Class[]) null);
                method.invoke(device, (Object[]) null);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

接收器捕获配对过程:

 private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                     final int state        = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
                     final int prevState    = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);

                     if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
                         showToast("Paired");
                     } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
                         showToast("Unpaired");
                     }

                }
            }
        };

注册接收者:

IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);