android - 蓝牙配对并连接设备

标签 android bluetooth connect

我想配对设备并连接它,但我遇到了问题,我只能配对设备但无法连接它们。我想知道如何解决这个问题。恐怕,我没有很好地解释我的问题,我无法连接意味着,将您的手机连接到蓝牙耳机,我只能配对,这是代码

 if (btAdapt.isEnabled()) {
                    tbtnSwitch.setChecked(false);
            } else {
                    tbtnSwitch.setChecked(true);
            }
            // ============================================================

            IntentFilter intent = new IntentFilter();
            intent.addAction(BluetoothDevice.ACTION_FOUND);
            intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
            intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
            intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(searchDevices, intent);
    }

    private BroadcastReceiver searchDevices = new BroadcastReceiver() {

            public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    Bundle b = intent.getExtras();
                    Object[] lstName = b.keySet().toArray();


                    for (int i = 0; i < lstName.length; i++) {
                            String keyName = lstName[i].toString();
                            Log.e(keyName, String.valueOf(b.get(keyName)));
                    }
                    BluetoothDevice device = null;

                    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                            device = intent
                                            .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                                    String str = "no pair|" + device.getName() + "|"
                                                    + device.getAddress();
                                    if (lstDevices.indexOf(str) == -1)
                                            lstDevices.add(str); 
                                    adtDevices.notifyDataSetChanged();
                            }
                    }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
                            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                            switch (device.getBondState()) {
                            case BluetoothDevice.BOND_BONDING:
                                    Log.d("BlueToothTestActivity", "it is pairing");
                                    break;
                            case BluetoothDevice.BOND_BONDED:
                                    Log.d("BlueToothTestActivity", "finish");
                                    connect(device);
                                    break;
                            case BluetoothDevice.BOND_NONE:
                                    Log.d("BlueToothTestActivity", "cancel");
                            default:
                                    break;
                            }
                    }

            }
    };

    @Override
    protected void onDestroy() {
            this.unregisterReceiver(searchDevices);
            super.onDestroy();
            android.os.Process.killProcess(android.os.Process.myPid());
    }

    class ItemClickEvent implements AdapterView.OnItemClickListener {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
            {
                    if(btAdapt.isDiscovering())btAdapt.cancelDiscovery();
                    String str = lstDevices.get(arg2);
                    String[] values = str.split("\\|");
                    String address = values[2];
                    Log.e("address", values[2]);
                    BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
                    try {
                            Boolean returnValue = false;
                            if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
                                  BluetoothDevice.createBond(BluetoothDevice remoteDevice);
                                    Method createBondMethod = BluetoothDevice.class
                                                    .getMethod("createBond");
                                    Log.d("BlueToothTestActivity", "start");
                                    returnValue = (Boolean) createBondMethod.invoke(btDev);

                            }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
                                    connect(btDev);
                            }
                    } catch (Exception e) {
                            e.printStackTrace();
                    }

            }

    }

    private void connect(BluetoothDevice btDev) {
            UUID uuid = UUID.fromString(SPP_UUID);
            try {
                    btSocket = btDev.createInsecureRfcommSocketToServiceRecord(uuid);
                    Log.d("BlueToothTestActivity", "connecting...");
                    btSocket.connect();
            } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            }
    }

    class ClickEvent implements View.OnClickListener {
            public void onClick(View v) {
                    if (v == btnSearch)
                    {
                            if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {
                                    Toast.makeText(BlueToothTestActivity.this, "please open", 1000)
                                                    .show();
                                    return;
                            }
                            if (btAdapt.isDiscovering())
                                    btAdapt.cancelDiscovery();
                            lstDevices.clear();
                            Object[] lstDevice = btAdapt.getBondedDevices().toArray();
                            for (int i = 0; i < lstDevice.length; i++) {
                                    BluetoothDevice device = (BluetoothDevice) lstDevice[i];
                                    String str = "pair|" + device.getName() + "|"
                                                    + device.getAddress();
                                    lstDevices.add(str); 
                                    adtDevices.notifyDataSetChanged();
                            }
                            setTitle("address:" + btAdapt.getAddress());
                            btAdapt.startDiscovery();
                    } else if (v == tbtnSwitch) {
                            if (tbtnSwitch.isChecked() == false)
                                    btAdapt.enable();

                            else if (tbtnSwitch.isChecked() == true)
                                    btAdapt.disable();
                    } else if (v == btnDis)
                    {
                            Intent discoverableIntent = new Intent(
                                            BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                            discoverableIntent.putExtra(
                                            BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                            startActivity(discoverableIntent);
                    } else if (v == btnExit) {
                            try {
                                    if (btSocket != null)
                                            btSocket.close();
                            } catch (IOException e) {
                                    e.printStackTrace();
                            }
                            BlueToothTestActivity.this.finish();
                    }
            }

    }

最佳答案

您没有指定,但我认为您的问题出在套接字创建部分,而不是实际的 connect() 调用。这是通常会出错的地方。

如何修复?

  1. 您的代码假定耳机支持不安全的 BT 通信。在许多情况下这是真的,但并非全部如此。尝试改为调用 createRfcommSocketToServiceRecord()

  2. 您的代码使用默认的 SPP UUID 进行 RFCOMM channel 查找。对于 >= 15 的 API 版本,这是错误的做法。而是尝试调用 device.getUuids() 并使用第一个返回的 UUID 作为创建参数。 根据我自己的经验,即使对于 15 之前的 API 版本,您仍然可以调用 getUuids() 并获得良好的结果,但您需要通过反射来完成。仅当上述操作失败时,您才应尝试使用默认 SPP UUID 创建套接字

  3. 如果上述方法失败,作为最后的手段,您可以尝试激活“createRfcommSocket”隐藏 API。这对我有用过好几次,而且适用于多个 Android 版本。使用 java 反射来激活此调用,并且由于本质上不安全,因此使用 try catch 对其进行保护。

  4. 请记住将您的逻辑放在 AsyncTask 或其他东西中。您不希望 UI 线程阻塞此类任务!

终于可以放心使用了https://github.com/giladHaimov/BTWiz用于更简单地处理蓝牙连接和简单的异步 IO 接口(interface)。

关于android - 蓝牙配对并连接设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12452888/

相关文章:

android - UNINSTALL_SHORTCUT 操作无效 |安卓

android - 如何在Android中获取通过蓝牙、WiFi传输的文件的详细信息

java - 如何使用 bluecove 在 Java 中断开 BT 设备?

javascript - 如何通过蓝牙发送Android命令?

android - HttpUrlConnection.connect 抛出异常

android - 使用模拟器设备 wifi 在模拟器上运行 android 应用程序

android - java.lang.IllegalArgumentException : Rect should intersect with child's bounds

java - 是否可以为android应用程序设置修复进程ID?

node.js - 如何更改快速静态目录?

由于 VPN,Apache Drill-embedded 无法连接