有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android蓝牙广播接收器未接收

我们有一个硬件,可以尝试连接到安卓手机,所以在安卓手机上打开服务器插座并监听就可以了

我现在遇到的问题是,我们有一个广播接收器在监听ACL_已连接和ACL_已断开

广播接收器没有接收到这些事件,服务器socket也没有接收来自硬件的连接,只是停留在accept()方法

为了让它工作,我必须先从安卓手机连接到硬件,然后从那时起,我将获得所有ACL_已连接/ACL_已断开连接的事件,我的服务器socket正在接受来自硬件的连接

这是正常行为吗?Android必须先与硬件连接一次,然后才能接收ACL_CONNECTED/ACL_DISCONNECTED事件?一旦我这么做了,我会一直收到事件,直到我喜欢在设备上重置出厂设置,然后又是同一个问题

谢谢


共 (1) 个答案

  1. # 1 楼答案

    如果没有提供任何代码,就很难找出到底是哪里出了问题。不过,我要猜一猜。连接失败的最常见原因是没有提供适当的UUID

    在大多数情况下,打印机、键盘、耳机等常见设备的最通用UUID是00001101-0000-1000-8000-00805F9B34FB。当你要求你的手机连接到这样一个设备,而你已经使用了这个UUID的大部分时间,它将连接。但是,当您告诉硬件设备连接到手机(初始化连接)时,如果它没有适合您手机的UUID,则无法建立连接

    总之: 检查UUID定义

    更新

    你的android端代码看起来像这样吗

    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;
     
            // Get a BluetoothSocket to connect with the given BluetoothDevice
            try {
                // MY_UUID is the app's UUID string, also used by the server code
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) { }
            mmSocket = tmp;
        }
     
        public void run() {
            // Cancel discovery because it will slow down the connection
            mBluetoothAdapter.cancelDiscovery();
     
            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
            } catch (IOException connectException) {
                // Unable to connect; close the socket and get out
                try {
                    mmSocket.close();
                } catch (IOException closeException) { }
                return;
            }
     
            // Do work to manage the connection (in a separate thread)
            manageConnectedSocket(mmSocket);
        }
     
        /** Will cancel an in-progress connection, and close the socket */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
    

    如果是这种情况,那么它是客户机而不是服务器。你的硬件正在监听客户端连接到它,而不是反过来