【问题标题】:Android BluetoothSocket can't connectAndroid BluetoothSocket无法连接
【发布时间】:2019-09-12 14:59:21
【问题描述】:

我正在使用 android 上的蓝牙做一些事情,我想连接到其中一个发现的设备并打开一个指向它的套接字连接。

我已授予所有需要的权限:Bluetooth、Bluetooth_Admin、Access_Fine_Location 和 Access_Coarse_Location,并在我对蓝牙进行任何操作之前请求它们。

现在,我发现了一些带有adapter.startDiscovery(); 和activity.registerReceiver(receiver, filter); 的设备

在接收器中找到某个名称的设备,我尝试像这样连接它:

            adapter.cancelDiscovery();
            Log.d(TAG, "Create Bond");
            device.createBond();
            try {
                socket = device.createRfcommSocketToServiceRecord(uuid);
                Log.d(TAG, "Sleep 10");
                sleep(10000);
                Log.d(TAG, "Create Socket");
                //socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                Log.d(TAG, "Connect socket");
                socket.connect();
                Log.d(TAG, "Connecting Done");
            } catch (Exception e) {
                Log.d(TAG, "Failed to connect to device", e);
                try {
                    socket.close();
                } catch (Exception e2) {
                    Log.d(TAG, "Failed to close socket", e2);
                }
            }

这是一个测试代码,我试图用它来创建一个套接字并打开一个连接。

我在 .connect() 上收到以下异常:

java.io.IOException: 读取失败,socket 可能关闭或超时,读取 回复:-1 在 android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:684) 在 android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:696) 在 android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:373)

我做错了什么。

我连接的蓝牙设备是 Android 移动设备,但我打算在连接成功后使用其他设备。

更新1: 安卓版本为7.0

【问题讨论】:

    标签: java android sockets bluetooth


    【解决方案1】:

    使用 fetchUuidsWithSdp() 和 getUuids() 查找所有已发布的服务及其关联的 UUID 值。

    【讨论】:

    • 抱歉,您能详细说明一下吗?忘了说了,我用 UUID.randomUUID(); 生成一个随机 UUID;
    • 哦等等,我应该使用设备 UUID 吗?我认为 createRF..Socket(uuid) 中的 UUID 变量是我的 UUID,而不是设备?
    【解决方案2】:

    您无需拨打device.createBond(); 即可连接蓝牙设备。

    尝试删除此行。另请检查您的手机是否尚未与您尝试连接的设备配对。 您可以在蓝牙设置屏幕上查看(长按智能手机上的蓝牙图标将其打开。

    这是一个启动蓝牙连接的示例代码:

    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
    
        public ConnectThread(BluetoothDevice device) {
            // Use a temporary object that is later assigned to mmSocket
            // because mmSocket is final.
            BluetoothSocket tmp = null;
            mmDevice = device;
    
            try {
                // Get a BluetoothSocket to connect with the given BluetoothDevice.
                // MY_UUID is the app's UUID string, also used in the server code.
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "Socket's create() method failed", e);
            }
            mmSocket = tmp;
        }
    
        public void run() {
            // Cancel discovery because it otherwise slows down the connection.
            bluetoothAdapter.cancelDiscovery();
    
            try {
                // Connect to the remote device through the socket. This call blocks
                // until it succeeds or throws an exception.
                mmSocket.connect();
            } catch (IOException connectException) {
                // Unable to connect; close the socket and return.
                try {
                    mmSocket.close();
                } catch (IOException closeException) {
                    Log.e(TAG, "Could not close the client socket", closeException);
                }
                return;
            }
    
            // The connection attempt succeeded. Perform work associated with
            // the connection in a separate thread.
            manageMyConnectedSocket(mmSocket);
        }
    
        // Closes the client socket and causes the thread to finish.
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "Could not close the client socket", e);
            }
        }
    }
    

    此代码来自Android官方文档: https://developer.android.com/guide/topics/connectivity/bluetooth#ConnectAsAClient

    【讨论】:

    • 嗯,connect 使用它吗?因为异常是在 .connect() 行触发的,所以我不使用 readCharacteristic()
    • 为什么我不应该使用 device.createBond()?顺便说一句,我可能已经想通了,因为我正在调用一个套接字创建,另一端应该有另一个服务器套接字接收这个连接是吗?而我没有。
    • 我确认您无需与设备配对即可连接。使用官方文档中的示例代码查看我的答案。您的蓝牙外围设备应该是 BLE 广告并且当前未连接 BLE。
    • 我实际上第一次尝试了这段代码,我得到了同样的错误。我会再试一次。
    • 您尝试连接的设备上运行的 Android 版本是什么?你检查过这个答案吗:stackoverflow.com/a/25647197/2068732
    【解决方案3】:

    我编写了另一个代码,而不是用于服务器端的代码。

                Log.d(TAG,"Start server");
                BluetoothServerSocket serverSocket = null;
                try {
                    serverSocket = adapter.listenUsingRfcommWithServiceRecord("ime", uuid);
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                while (true) {
                    try {
                        serverSocket.accept();
                    } catch (Exception e) {
                        e.printStackTrace();
    
                    }
                }
    

    我在一个启动的线程中使用了这段代码,而不是从问题中调用代码。

    在一个应用程序上安装带有服务器代码的应用程序并在套接字上调用“连接”就可以了。 我使用了相同的 UUID(以前是随机生成的,新的是来自字符串的静态)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 2016-08-18
      • 2016-04-24
      相关资源
      最近更新 更多