Android System.err断开蓝牙连接

时间:2012-09-02 13:36:32

标签: android bluetooth

我正试图尽可能优雅地与蓝牙设备断开连接,但Android坚持要求系统错误:

09-02 15:16:16.748: W/System.err(31038): java.io.IOException: Operation Canceled
09-02 15:16:16.748: W/System.err(31038):    at android.bluetooth.BluetoothSocket.readNative(Native Method)
09-02 15:16:16.748: W/System.err(31038):    at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:333)
09-02 15:16:16.748: W/System.err(31038):    at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:60)
09-02 15:16:16.748: W/System.err(31038):    at com.bluetooth.BluetoothRemoteControlApp$ConnectedThread.run(BluetoothRemoteControlApp.java:207)

我正在使用BluetoothChat示例程序的修改版本,我的连接线程如下:

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) {
            e.printStackTrace();
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;

        connected = true;
    }

    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;
        byte ch;

        while(connected) {
            try {
                bytes = 0;
                while((ch = (byte) mmInStream.read()) != '\n')
                {
                    buffer[bytes++] = ch;
                }

                busy = false;

                String msg = new String(buffer, "UTF-8").substring(0, bytes - 1);

                Log.d(TAG, "Read: " + msg);

                if(activityHandler != null) {
                    activityHandler.obtainMessage(BT_READ, bytes, 0, msg).sendToTarget();
                }

            }
            catch(IOException e) {
                //e.printStackTrace();
                Log.w(TAG, "Cancelling");
                break;
            }
        }
    }

    public void write(byte[] buffer) {
        // . . .
    }

    public void cancel() {
        Log.i(TAG, "Cancelling connected thread");
        try {
            mmSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在断开连接期间,我调用了取消方法,该方法会引发系统错误。我应该担心并尝试解决它吗?我真的不喜欢在日志中看到错误...

2 个答案:

答案 0 :(得分:1)

我不认为您应该过于担心此日志,因为您正在取消并且日志本身会显示Operation Cancelled

我认为您在run方法中使用e.printStacktrace打印日志。这就是你看到这个日志的原因。

答案 1 :(得分:0)

也许你应该在取消方法中将连接设置为false。