Android的蓝牙连接问题 [英] Android Bluetooth connection issue

查看:185
本文介绍了Android的蓝牙连接问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试建立如下蓝牙连接:

I try to set up a Bluetooth connection as follow :

    private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    BluetoothSocket connection = null;

    public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice            
        try {


            if(D) Log.i(TAG, "createRfcommSocket");
            Method m = mmDevice.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
            connection = (BluetoothSocket) m.invoke(mmDevice, 1);

            Utils.pause(100);
        } catch (Exception e) {
            Log.e(TAG, "create() failed", e);
        }
        if(D) Log.i(TAG,"Bluetooth socket initialised");
        mmSocket = connection;
    }

    public void run() {
        if(D) Log.i(TAG, "BEGIN mConnectThread on Device : " + mmDevice);
        setName("ConnectThread");

        if (mmSocket != null) {
            // Always cancel discovery because it will slow down a connection
            if(mAdapter.isDiscovering()) {
                if(D) Log.i(TAG, "stop discovering before trying to connect");
                mAdapter.cancelDiscovery();
            }

            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                if(D) Log.i(TAG, "start Bluetooth socket connection");
                mmSocket.connect();
                if(D) Log.i(TAG, "end of Bluetooth socket connection");
            } catch (Exception e1) {
                Log.e(TAG, "connect failed", e1);
                connectionFailed();
                // Reset the socket
                resetConnection(mmSocket);
                // Start the service over to restart listening mode
                if(D) Log.i(TAG, "restart connection");
                BluetoothConnectionService.this.start();
                if(D) Log.i(TAG, "return");
                return;
            }

            // Start the connected thread
            if(D) Log.i(TAG, "The device is considered as connected, call connected thread");
            connected(mmSocket, mmDevice);
        } else {
            if(D) Log.i(TAG, "connection fail");
            connectionFailed();
            BluetoothConnectionService.this.start();
        }
    }

    public void cancel() {
        if(D) Log.i(TAG,"connect thread cancel");
        resetConnection(mmSocket);
    }
}

连接似乎是好了,我得到这个日志:

The connection seems to be OK, I get this log :

DEBUG/BluetoothConnectionService(3439): **connect to: 00:18:E4:21:8B:5E**
INFO/BluetoothConnectionService(3439): createRfcommSocket
INFO/BluetoothConnectionService(3439): Bluetooth socket initialised
INFO/BluetoothConnectionService(3439): BEGIN mConnectThread on Device : 00:18:E4:21:8B:5E
INFO/BluetoothConnectionService(3439): **start Bluetooth socket connection**
INFO/BluetoothConnectionService(3439): setState() 1 -> 2
INFO/ProtectionService(3439): MESSAGE_STATE_CHANGE: 1
DEBUG/ProtectionService(3439): STATE_CHANGED to STATE_LISTEN
INFO/ProtectionService(3439): MESSAGE_STATE_CHANGE: 2
DEBUG/abtfilt(2772): **Conn complete**
INFO/bluetoothd(2776): link_key_request (sba=24:21:AB:F4:69:25, dba=00:18:E4:21:8B:5E)
INFO/bluetoothd(2776): link_key_request (sba=24:21:AB:F4:69:25, dba=00:18:E4:21:8B:5E)
INFO/BluetoothConnectionService(3439): **end of Bluetooth socket connection**
INFO/BluetoothConnectionService(3439): **The device is considered as connected, call connected thread**

BluetoothSocket.connect()返回没有错误。

然后我管理这个连接:

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

    public ConnectedThread(BluetoothSocket socket) {
        if(D) Log.d(TAG, "create ConnectedThread");
        mmSocket = socket;

        // Get the BluetoothSocket input and output streams
        try {
            if(D) Log.i(TAG, "Get input stream");
            tmpIn = socket.getInputStream();
            if(D) Log.i(TAG, "Get output stream");
            tmpOut = socket.getOutputStream();
            if(D) Log.i(TAG, "isConnected = true");
            isConnected = true;
        } catch (IOException e) {
            Log.e(TAG, "Input and Output sockets not created", e);
            isConnected = false;
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        if(D) Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024]; //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
                if(D) Log.i(TAG, "start read mmInStream");
                bytes = mmInStream.read(buffer);
                if(D) Log.i(TAG, "Bytes read : "+bytes);

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

    /**
     * Write to the connected OutStream.
     * 
     * @param buffer
     *            The bytes to write
     */
    public void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);

            // Share the sent message back to the UI Activity
            mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
            // mmOutStream.flush();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
            connectionFailed();
        }
    }

    public void cancel() {
        if(D) Log.i(TAG,"connected Thread cancel");
        resetConnection(mmSocket);

    }
}

和我收到此错误:

DEBUG/BluetoothConnectionService(3439): create ConnectedThread
INFO/BluetoothConnectionService(3439): Get input stream
INFO/BluetoothConnectionService(3439): Get output stream
INFO/BluetoothConnectionService(3439): isConnected = true
INFO/BluetoothConnectionService(3439): BEGIN mConnectedThread
INFO/BluetoothConnectionService(3439): start read mmInStream
INFO/BluetoothConnectionService(3439): setState() 2 -> 3
INFO/ProtectionService(3439): MESSAGE_STATE_CHANGE: 3
DEBUG/ProtectionService(3439): connectionEstablished
**ERROR/BluetoothConnectionService(3439): ConnectedThread : disconnected
ERROR/BluetoothConnectionService(3439): java.io.IOException: Software caused connection abort
ERROR/BluetoothConnectionService(3439):     at android.bluetooth.BluetoothSocket.readNative(Native Method)
ERROR/BluetoothConnectionService(3439):     at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:307)
ERROR/BluetoothConnectionService(3439):     at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
ERROR/BluetoothConnectionService(3439):     at java.io.InputStream.read(InputStream.java:133)**
INFO/ProtectionService(3439): Send Bluetooth message
**ERROR/BluetoothConnectionService(3439): Exception during write
ERROR/BluetoothConnectionService(3439): java.io.IOException: Transport endpoint is not connected
ERROR/BluetoothConnectionService(3439):     at android.bluetooth.BluetoothSocket.writeNative(Native Method)
ERROR/BluetoothConnectionService(3439):     at android.bluetooth.BluetoothSocket.write(BluetoothSocket.java:317)**

这个错误清楚地到来,当我这样做:

The error clearly come when I am doing this :

bytes = mmInStream.read(buffer);

我是什么做错了吗?我工作的这个错误了一个星期,我无法通过......

What am I doing wrong ? I'm working on this error for a week and I can't go through...

任何帮助将是非常一个preciated!

Any help would be very apreciated !

推荐答案

我前几天有一个非常类似的问题...

I had a very similar problem some days ago...

尝试增加这个检查你的code:

Try adding this check to your code:

if(mmInStream.available() > 0){
   bytes = mmInStream.read(buffer);
   mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
}

这固定我的问题...

This fixed my problem...

好运;)

这篇关于Android的蓝牙连接问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆