Android蓝牙并不总是接收数据

时间:2017-06-20 16:22:32

标签: java android bluetooth

我有一个令人沮丧的问题,即我的串行蓝牙接收代码并不总是从它的连接中接收数据。大多数情况下,它运行良好,但有时连接后,即使我可以验证连接是否存在,并且其他设备正在发送数据,它也不会接收任何数据。我的接收代码如下:

    /**
 * Created by tvanderpuy on 12/1/2016.
 * Handles communication with BT device
 */

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

    public ConnectedThread(BluetoothSocket socket) {
        Log.d(TAG, "create ConnectedThread");
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;

        // Set up buffered reader
        bufferedReader = new BufferedReader(new InputStreamReader(mmInStream));
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()
        String cmd;

        // Keep listening to the InputStream until an exception occurs
        while (mState == STATE_CONNECTED) {
            try {
                // Wait for new line for buffered reader
                cmd = bufferedReader.readLine();

                // Send the obtained bytes to the UI activity
                if (!cmd.isEmpty())
                    mHandler.obtainMessage(MESSAGE_READ, cmd.getBytes().length, -1, cmd.getBytes())
                            .sendToTarget();
                Log.v(TAG, "Command: " + cmd);
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();

                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) {
        }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
        }
    }
}

}

如果您对此有任何见解,请与我们联系。 谢谢, 汤姆

0 个答案:

没有答案