Программное соединение между устройством Android и Bluetooth-гарнитурой - PullRequest
0 голосов
/ 29 августа 2018

Как я могу сделать приложение для Android, которое может обеспечить соединение между устройством Android и динамиками Bluetooth.

1 Ответ

0 голосов
/ 29 августа 2018

Как создать пару:

   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);
...