【问题标题】:Android BluetoothSocket connection returns zeroAndroid BluetoothSocket 连接返回零
【发布时间】:2016-04-26 13:41:25
【问题描述】:

我们的设备通过蓝牙发送数据,在安卓应用中我们需要读取这些数据。

我能够建立蓝牙连接,接下来我调用一个线程来使用蓝牙设备建立蓝牙套接字连接。在这里,当读取字节时,它返回 0(零) 此外,while 循环只运行一次。

我在下面的代码中使用的 UUID 也来自一些蓝牙片段代码。是否需要获取设备的正确 UUID。

任何人都可以帮忙吗?如果您给我有用的答案,我们将不胜感激。

   //Calling ConnectThread after Bluetooth is paired
    public class ConnectThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final BluetoothDevice mmDevice;
            private final UUID MY_UUID = UUID
                    .fromString("00001101-0000-1000-8000-00805f9b34fb");

            public ConnectThread(BluetoothDevice device) {
                BluetoothSocket tmp = null;
                mmDevice = device;
                try {
                    String name = device.getName();
                    Log.e("Device Name ", name);
                    tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e) {
                }
                mmSocket = tmp;
            }

            public void run() {
                // mAdapter.cancelDiscovery();
                try {
                    mmSocket.connect();

                    ConnectedThread mConnectedThread = new ConnectedThread(mmSocket);
                    mConnectedThread.start();
                } catch (IOException connectException) {
                    // try {
                    // mSocket.close();
                    // } catch (IOException closeException) { }
                    return;
                }
            }

            public void cancel() {
                try {
                    mmSocket.close();
                } catch (IOException e) {
                }
            }
        }

        private class ConnectedThread extends Thread {
            private final BluetoothSocket mmSocket;
            private final InputStream mmInStream;
            private final OutputStream mmOutStream;

            public ConnectedThread(BluetoothSocket socket) {
                mmSocket = socket;
                InputStream tmpIn = null;
                OutputStream tmpOut = null;
                try {
                    tmpIn = socket.getInputStream();
                    tmpOut = socket.getOutputStream();
                } catch (IOException e) {
                }
                mmInStream = tmpIn;
                mmOutStream = tmpOut;
            }

            public void run() {
                byte[] buffer = new byte[1024];
                int begin = 0;
                int bytes = 0;
                while (true) {
                    try {
                        // bytes += mmInStream.read(buffer, bytes, buffer.length
                        // - bytes);
                        if (mmSocket.isConnected()) {
                            Log.e("Socket is connected", "Socket is connected");
                        }
                        int numOfBytes = mmInStream.available();
                        Log.e("numOfBytes", String.valueOf(+numOfBytes));
                        bytes = mmInStream.read(buffer);

                        // mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        // .sendToTarget();



                    } catch (IOException e) {
                        break;
                    }
                }
            }


i am struck and unable to read the data from the Bluetooth

【问题讨论】:

    标签: android android-bluetooth bluetooth-socket


    【解决方案1】:

    我是否需要获取设备的正确 UUID。

    是的。您可以使用 BluetoothDevice 中的 getUuids() 来返回远程设备支持的功能 (UUID),如果需要新的 UUID,则可以使用 fetchUuidsWithSdp()

    while 循环只运行一次。

    这是因为你的代码抛出了一个错误,而你正在处理这个错误并退出循环

                while (true) {
                    try {
                        // bytes += mmInStream.read(buffer, bytes, buffer.length
                        // - bytes);
                        if (mmSocket.isConnected()) {
                            Log.e("Socket is connected", "Socket is connected");
                        }
                        int numOfBytes = mmInStream.available();
                        Log.e("numOfBytes", String.valueOf(+numOfBytes));
                        bytes = mmInStream.read(buffer);
    
                        // mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        // .sendToTarget();
    
    
    
                    } catch (IOException e) {
                        // THIS BREAK INTERRUPT YOUR WHILE-LOOP SENTENCE
                        break;
                    }
                }
    

    读取字节时返回 0

    因为您创建了一个未连接到任何东西的套接字的 InputStream(因为您创建用于生成套接字的 UUID 在您进行蓝牙连接的设备中不存在)

    编辑

    获取 uuid 的其他方法是配置广播接收器以取回 uuid:

    //Register the BroadcastReceiver
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothDevice.ACTION_UUID);
    //Set your other filters
    registerReceiver(ActionFoundReceiver, filter); // Don't forget to unregister during onDestroy
    

    并创建您的 BroadcastRecievier 以获取 UUID:

      private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){
    
        @Override
        public void onReceive(Context context, Intent intent) {
         String action = intent.getAction();
    
           if(BluetoothDevice.ACTION_UUID.equals(action)) {
             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
             Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
             for (int i=0; i<uuidExtra.length; i++) {
             Log.i("TEST-UUIDS","Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString());
             }
           } 
           else if(BluetoothDevice.YOUR_OTHER_ACTION_1){
            //YOUR CODE FOR ACTION 1
    
           } 
           else if(BluetoothDevice.YOUR_OTHER_ACTION_2){
            //YOUR CODE FOR ACTION 2
    
           } 
    
        }
      };
    

    注意:并非每个蓝牙设备都会显示其服务 uuid'

    【讨论】:

    • 感谢米格尔的回复。
    • 我尝试使用以下代码获取 Uuids。但是 device.getUuids();正在返回 null 。供您参考,BluetoothDevice 对象不为空,但 device.getUuids() 为空。 BluetoothDevice 设备;尝试 { ParcelUuid[] uuids = device.getUuids(); for (ParcelUuid ep : uuids) { Log.e("UUID records : ", ep.toString()); } } catch (Exception e) { Log.e("Exceptoin e", e.toString()); }
    • 你是用他的地址连接设备还是通过扫描发现他们连接设备?
    • 在发现设备时检查是否可以取回 uuids
    • 当套接字在 mmSocket.isConnected() if 语句中连接时,尝试读取您的输入流。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多