无法在android中的两个蓝牙设备之间发送文本数据?

时间:2013-06-11 09:52:06

标签: android bluetooth

我已经下载了蓝牙聊天应用程序的android示例,以便使用蓝牙在两个Android设备之间发送文本。

我已在两个Android设备中安装并运行此应用程序。

我在那段代码中遇到了很多问题

  1. 服务发现失败例外 - 已修复
  2. java.io.IOException:软件导致连接中止 - 已修复
  3. java.io.IOException:Peer连接重置 - 触发此
  4. 1。清除了服务发现失败的异常:

    对于服务发现失败的异常,在蓝牙聊天服务中,我检查了sdk版本,并且检查了比Ginger Bread更大的sdk版本,

    我使用了Method类来调用RfCOMM套接字连接,这个方法解决了我的第一个异常。

    例外代码

     tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
    

    修正了例外代码

    try {
    if (Build.VERSION.SDK_INT < 9) { 
    try {
         tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
           } catch (IOException e1) {
                e1.printStackTrace();
           }
           } else {
       Method m = null;
      try {
      m = device.getClass().getMethod("createRfcommSocket",
            new Class[] { int.class });
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                    }
                    try {
                        tmp = (BluetoothSocket) m.invoke(device, 1);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "create() failed", e);
                }
    

    2。清除java.io.IOException:软件导致连接中止

    我已经检查了InputStream是否可用

    例外代码

    bytes = mmInStream.read(buffer);
    

    修正了例外代码

     if (mmInStream.available() > 0) {
                                // Read from the InputStream
                                bytes = mmInStream.read(buffer);
    
      

    现在我的问题是当我尝试在连接的设备之间发送数据时,它会在写入输出流时抛出以下错误消息“Connection Reset By Peer”

    例外代码:

    public void write(byte[] buffer, int start, int end) {
    mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
        if (mmOutStream !=null) {
            try {
                 mmOutStream.write(buffer);
            } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
            }
        }
        else{
            Log.e("OutputStream Null","");
        }
    }
    

    ==更新==

    即使它显示两个设备都已连接,但accept方法返回失败

    **06-19 10:30:23.625: D/BluetoothChatService(2630): connected
    06-19 10:30:23.625: D/BluetoothChatService(2630): cancel Thread[AcceptThread,5,main]
    06-19 10:30:23.625: V/BluetoothSocket.cpp(2630): abortNative
    06-19 10:30:23.625: V/BluetoothSocket.cpp(2630): ...asocket_abort(50) complete
    06-19 10:30:23.625: V/BluetoothSocket.cpp(2630): ...accept(50, RFCOMM) = -1 (errno 125)
    06-19 10:30:23.632: E/BluetoothChatService(2630): accept() failed
    06-19 10:30:23.632: E/BluetoothChatService(2630): java.io.IOException: Operation Canceled
    06-19 10:30:23.632: E/BluetoothChatService(2630):   at android.bluetooth.BluetoothSocket.acceptNative(Native Method)
    

3 个答案:

答案 0 :(得分:1)

我自己的聊天示例有很多问题,所以我尝试了另一种方法。

首先,您必须创建一个设备主机,而另一个设备客户端,这很好地适用于该示例。如果你没有这个运行,我也可以为你提供该代码。

使用上面的类,您将获得连接的套接字。使用它将它传递给这个类,然后你可以使用write方法发送。并且在run-method中自动解析传入的消息(我在前面添加了一个消息id和长度,这就是为什么那里有很多事情发生的事情)

private class ConnectedThread extends Thread {

/** the connection socket */
private final BluetoothSocket mmSocket;

/** input stream for incoming messages */
private final InputStream mmInStream;

/** output stream for outgoing messages */
private final OutputStream mmOutStream;

/**
 * save the socket and get the streams
 * 
 * @param socket
 */
public ConnectedThread(BluetoothSocket socket) {
    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) {
        e.printStackTrace();
    }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
}

/**
 * reads incoming data and splits it into single messages
 */
public void run() {
    /** buffer for a single byte message */
    byte[] buffer = new byte[1024];

    /** number of bytes returned from read() */
    int bytes;

    // Keep listening to the InputStream until an exception occurs
    while (true) {
        try {
            // read overhead from the InputStream
            bytes = mmInStream.read(buffer, 0, LEN_SIZE + LEN_TYPE);

            // if no bytes are read, wait for a new message
            if (bytes == 0)
                continue;

            // get the size bytes and convert them to int
            byte[] size_arr = new byte[LEN_SIZE];
            for (int i = 0; i < LEN_SIZE; i++)
                size_arr[i] = buffer[i];
            int size = convertByteArrayToInt(size_arr, LEN_SIZE);

            // the type is 1 byte after the size
            byte type = buffer[LEN_SIZE];

            // array for the output data
            byte[] output = new byte[size + LEN_TYPE];
            output[0] = type;

            // current position, read until cPos == size
            int cPos = 0;
            while (cPos < size) {
                // either read the buffer lenght or the remaining bytes
                int read_len = Math.min(buffer.length, size - cPos);
                bytes = mmInStream.read(buffer, 0, read_len);

                // write the bytes to the output
                for (int i = 0; i < bytes; i++)
                    output[cPos + i + LEN_TYPE] = buffer[i];

                // increase the current position
                cPos += bytes;
            }

            // add the message to the queue
            mMessageData.add(output);

            // tell the service about the new message
            mHandler.obtainMessage(BluetoothService.CONNECTION_RECV_MSG, mConnectionAddress).sendToTarget();

        } catch (IOException e) {
            // tell the service about the disconnect
            mHandler.obtainMessage(BluetoothService.CONNECTION_LOST, mConnectionAddress).sendToTarget();
            e.printStackTrace();
            break;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * writes a byte stream to the connection
 * 
 * @param bytes
 *            the byte stream
 */
public void write(byte[] bytes) {
    try {
        mmOutStream.write(bytes, 0, bytes.length);
        mmOutStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * close the socket
 */
public void cancel() {
    try {
        mmSocket.close();
    } catch (IOException e) {
    }
}

}

这对我有用,我希望它也适合你。如果您有任何疑问,请随时询问: - )

答案 1 :(得分:0)

你可以试试这个,虽然它可能不应该是最后的修复。当我按照这个例子时,我的主要活动中有onResume(),我想你有类似的东西:

@Override
public synchronized void onResume() {
    super.onResume();
    if(D) Log.e(TAG, "+ ON RESUME +");
}

试试这个:

@Override
public synchronized void onResume() {
//    super.onResume();
    if(D) Log.e(TAG, "+ ON RESUME +");
}

这将阻止主要活动多次创建AcceptThread。

答案 2 :(得分:0)

我认为你的阅读是错误的。我有一行

while (true) {
    try {
        // read overhead from the InputStream
        bytes = mmInStream.read(buffer, 0, LEN_SIZE + LEN_TYPE);

在我的代码中它运行正常,没有.available(),@ gtRfnkN也是如此。根据我对Java文档的解释,您不能将.available()与InputStream一起使用。 请参阅:http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#available(),特别是其中“始终为类InputStream返回零”的部分。

以防万一,这是我写的一个例子:

    public void write(byte[] buffer){
        try{
            //a delay of 20ms occurs after each flush...
            mmOutStream.write((byte)buffer[0]);
            mmOutStream.flush();
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }