蓝牙无法正常工作

时间:2010-06-17 15:48:52

标签: android bluetooth

您好我想在Android设备之间进行对话。我使用BluetoothChat来做到这一点,但它不起作用我无法正确读取来自其他设备的数据。

会话是:

我:女贞

设备:p 装置:铆钉

你能帮助我吗?

私有类ConnectedThread扩展了线程{

    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

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

        int INPUT_BUFFER_SIZE=32;
        // Get the BluetoothSocket input and output streams
        try {
            //tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
            tmpIn = new BufferedInputStream(socket.getInputStream(),INPUT_BUFFER_SIZE);

        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int bytes;

        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream

              bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

解决方案的修复方法是在连接线程中创建字符串,直接在InputStream上调用read()之后,然后将字符串传递回主线程进行显示。无论出于何种原因,在线程之间传递字节数组会导致重复的重复和数据丢失。

修改后的run()代码:

public void run() {
    byte[] buffer = new byte[256];  // buffer store for the stream
    int bytes; // bytes returned from read()

    // Keep listening to the InputStream until an exception occurs
    while (true) {
        try {
            // Read from the InputStream
            bytes = mmInStream.read(buffer);
            String readMessage = new String(buffer, 0, bytes);
            // Send the obtained bytes to the UI Activity
            mHandler.obtainMessage(MESSAGE_READ, bytes, -1, readMessage)
                    .sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

处理程序接收:

case MESSAGE_READ:
        // Read in string from message, display to mainText for user
        String readMessage = (String) msg.obj;
        if (msg.arg1 > 0) {
            mainText.append(readMessage);
        }
相关问题