发布
社区首页 >问答首页 >android设备与蓝牙耳机的程序化连接

android设备与蓝牙耳机的程序化连接
EN

Stack Overflow用户
提问于 2018-08-29 16:53:17
回答 1查看 49关注 0票数 0

如何在android中创建一个应用程序,以便在android设备和蓝牙扬声器之间提供连接。

EN

回答 1

Stack Overflow用户

发布于 2018-08-29 17:12:46

如何配对:

代码语言:javascript
代码运行次数: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();
            }
        }

如何解除配对:

代码语言:javascript
代码运行次数:0
复制
 private void unpairDevice(BluetoothDevice device) {
            try {
                Method method = device.getClass().getMethod("removeBond", (Class[]) null);
                method.invoke(device, (Object[]) null);

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

捕获配对过程的接收方:

代码语言:javascript
代码运行次数:0
复制
 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");
                     }

                }
            }
        };

寄存器接收器:

代码语言:javascript
代码运行次数:0
复制
IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52073337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档