Android:蓝牙 - 无法建立连接,IOException“连接由对等方重置”

发布于 2024-11-05 19:20:34 字数 6634 浏览 0 评论 0原文

如果有人能帮助我,我将非常感激。我正在尝试连接到客户提供给我的一些自定义蓝牙硬件。我严格遵循 API 文档,并使用以下代码(大部分是从官方文档复制并缝合在一起)来建立与蓝牙硬件的套接字连接,用户从我的 Android 应用程序中的列表视图中选择该硬件作为设备。

private class CommunicationThread extends Thread {
    private final BluetoothSocket mmSocket;

    public CommunicationThread(BluetoothDevice device) {
        super();
        // use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // create rf communication socket using a unique identifier for this app
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
        } catch (Exception e) {
            Log.d("An exception occurred during bluetooth rf communication server socket creation","NDB",e);
        }
        mmSocket = tmp;

        // cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();
    }

    public void run() {
        try {
            // connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException e) {
            Log.d("An exception occurred during bluetooth socket connection","NDB",e);
            // unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeExc) {
                Log.d("An exception occurred while attempting to close bluetooth socket","NDB",closeExc);
            }
            return;
        }

        // do work to manage the connection
        manageConnectedSocket();
    }

    private void manageConnectedSocket() {
        InputStream tmpIn = null;

        // get the input steram, use temp object because
        // member stream is final
        try {
            tmpIn = mmSocket.getInputStream();
        } catch (IOException e) {
            Log.d("An exception occurred during bluetooth io stream creation","NDB",e);
        }

        final InputStream mmInStream = tmpIn;

        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
                bytes = mmInStream.read(buffer);
                // send the obtained bytes to the message handler
                bluetoothHandler.obtainMessage(/*MESSAGE_READ*/1, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /** Cancels an in-progress connection, and closes the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

问题是,在尝试使用 mmSocket.connect()run() 中连接到硬件时,调用会阻塞几秒钟,然后抛出一个异常,描述为 java.io.IOException:连接被对等方重置。我在下面粘贴了相关的 LogCat 输出,以及周围的行供您考虑。

05-07 13:29:08.675: INFO/ActivityThread(1370): Receiving broadcast android.bleutooth.device.action.UUID seq=-1 to android.app.ActivityThread$PackageInfo$ReceiverDispatcher@2fd75738
05-07 13:29:08.675: ERROR/ActivityThread(1370): start dispatch OnReceive message,mRegistered=true mCurOrdered=false intent=Intent { act=android.bleutooth.device.action.UUID (has extras) } receiver = com.android.settings.bluetooth.BluetoothEventRedirector$1@2fd74d98
05-07 13:29:08.675: VERBOSE/BluetoothEventRedirector(1370): Received android.bleutooth.device.action.UUID
05-07 13:29:08.675: ERROR/xubo(1370): mBroadcastReceiver receive msg = android.bleutooth.device.action.UUID
05-07 13:29:08.685: ERROR/ActivityThread(1370): exit dispatch OnReceive message,mRegistered=true mCurOrdered=false
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827): NDB
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827): java.io.IOException: Connection reset by peer
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827):     at android.bluetooth.BluetoothSocket.connectNative(Native Method)
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827):     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:204)
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827):     at com.ndb.proj.Communicator$CommunicationThread.run(Communicator.java:157)
05-07 13:29:18.595: DEBUG/bluez/src/device.c(8031): /org/bluez/8031/hci0/dev_00_06_66_05_70_E7: canceling authentication request
05-07 13:29:18.595: ERROR/BluetoothEventLoop.cpp(1204): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/8031/hci0/dev_00_06_66_05_70_E7
05-07 13:29:18.595: DEBUG/BluetoothEventLoop(1204): Device property changed:00:06:66:05:70:E7property:Connected
05-07 13:29:18.605: INFO/ActivityThread(1204): Receiving broadcast android.bluetooth.device.action.ACL_DISCONNECTED seq=-1 to android.app.ActivityThread$PackageInfo$ReceiverDispatcher@2fe7b918
05-07 13:29:18.605: ERROR/ActivityThread(1204): start dispatch OnReceive message,mRegistered=true mCurOrdered=false intent=Intent { act=android.bluetooth.device.action.ACL_DISCONNECTED (has extras) } receiver = android.server.BluetoothA2dpService$1@2fdafb58
05-07 13:29:18.615: ERROR/ActivityThread(1204): exit dispatch OnReceive message,mRegistered=true mCurOrdered=false
05-07 13:29:18.615: INFO/ActivityThread(1370): Receiving broadcast android.bluetooth.device.action.PAIRING_CANCEL seq=-1 to android.app.ActivityThread$PackageInfo$ReceiverDispatcher@2fd75738
05-07 13:29:18.625: ERROR/ActivityThread(1370): start dispatch OnReceive message,mRegistered=true mCurOrdered=false intent=Intent { act=android.bluetooth.device.action.PAIRING_CANCEL } receiver = com.android.settings.bluetooth.BluetoothEventRedirector$1@2fd74d98
05-07 13:29:18.625: VERBOSE/BluetoothEventRedirector(1370): Received android.bluetooth.device.action.PAIRING_CANCEL
05-07 13:29:18.625: ERROR/xubo(1370): mBroadcastReceiver receive msg = android.bluetooth.device.action.PAIRING_CANCEL
05-07 13:29:18.625: ERROR/ActivityThread(1370): exit dispatch OnReceive message,mRegistered=true mCurOrdered=false

客户告知“配对代码”是 1234。但是,我的 Android 手机与该设备配对良好,无需指定此代码。我已经通过输入蓝牙设置进行了验证,并且设备确实被报告为已配对。

任何人都可以建议出了什么问题吗?

I'd be very grateful if someone could help me. I'm trying to connect to some custom bluetooth hardware a client has provided me. I've followed the API docs religiously and am using the following code (mostly copied and sewn together from the official docs) to establish a socket connection with the bluetooth hardware, which a user selects as a device from a listview within my Android application.

private class CommunicationThread extends Thread {
    private final BluetoothSocket mmSocket;

    public CommunicationThread(BluetoothDevice device) {
        super();
        // use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // create rf communication socket using a unique identifier for this app
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
        } catch (Exception e) {
            Log.d("An exception occurred during bluetooth rf communication server socket creation","NDB",e);
        }
        mmSocket = tmp;

        // cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();
    }

    public void run() {
        try {
            // connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException e) {
            Log.d("An exception occurred during bluetooth socket connection","NDB",e);
            // unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeExc) {
                Log.d("An exception occurred while attempting to close bluetooth socket","NDB",closeExc);
            }
            return;
        }

        // do work to manage the connection
        manageConnectedSocket();
    }

    private void manageConnectedSocket() {
        InputStream tmpIn = null;

        // get the input steram, use temp object because
        // member stream is final
        try {
            tmpIn = mmSocket.getInputStream();
        } catch (IOException e) {
            Log.d("An exception occurred during bluetooth io stream creation","NDB",e);
        }

        final InputStream mmInStream = tmpIn;

        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
                bytes = mmInStream.read(buffer);
                // send the obtained bytes to the message handler
                bluetoothHandler.obtainMessage(/*MESSAGE_READ*/1, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /** Cancels an in-progress connection, and closes the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

The problem is that upon attempting to connect to the hardware within run() using mmSocket.connect() the call blocks for a few seconds then throws an exception with description java.io.IOException: Connection reset by peer. I've pasted the relevant LogCat output below, with surrounding lines for your consideration.

05-07 13:29:08.675: INFO/ActivityThread(1370): Receiving broadcast android.bleutooth.device.action.UUID seq=-1 to android.app.ActivityThread$PackageInfo$ReceiverDispatcher@2fd75738
05-07 13:29:08.675: ERROR/ActivityThread(1370): start dispatch OnReceive message,mRegistered=true mCurOrdered=false intent=Intent { act=android.bleutooth.device.action.UUID (has extras) } receiver = com.android.settings.bluetooth.BluetoothEventRedirector$1@2fd74d98
05-07 13:29:08.675: VERBOSE/BluetoothEventRedirector(1370): Received android.bleutooth.device.action.UUID
05-07 13:29:08.675: ERROR/xubo(1370): mBroadcastReceiver receive msg = android.bleutooth.device.action.UUID
05-07 13:29:08.685: ERROR/ActivityThread(1370): exit dispatch OnReceive message,mRegistered=true mCurOrdered=false
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827): NDB
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827): java.io.IOException: Connection reset by peer
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827):     at android.bluetooth.BluetoothSocket.connectNative(Native Method)
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827):     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:204)
05-07 13:29:15.455: DEBUG/An exception occurred during bluetooth socket connection(9827):     at com.ndb.proj.Communicator$CommunicationThread.run(Communicator.java:157)
05-07 13:29:18.595: DEBUG/bluez/src/device.c(8031): /org/bluez/8031/hci0/dev_00_06_66_05_70_E7: canceling authentication request
05-07 13:29:18.595: ERROR/BluetoothEventLoop.cpp(1204): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/8031/hci0/dev_00_06_66_05_70_E7
05-07 13:29:18.595: DEBUG/BluetoothEventLoop(1204): Device property changed:00:06:66:05:70:E7property:Connected
05-07 13:29:18.605: INFO/ActivityThread(1204): Receiving broadcast android.bluetooth.device.action.ACL_DISCONNECTED seq=-1 to android.app.ActivityThread$PackageInfo$ReceiverDispatcher@2fe7b918
05-07 13:29:18.605: ERROR/ActivityThread(1204): start dispatch OnReceive message,mRegistered=true mCurOrdered=false intent=Intent { act=android.bluetooth.device.action.ACL_DISCONNECTED (has extras) } receiver = android.server.BluetoothA2dpService$1@2fdafb58
05-07 13:29:18.615: ERROR/ActivityThread(1204): exit dispatch OnReceive message,mRegistered=true mCurOrdered=false
05-07 13:29:18.615: INFO/ActivityThread(1370): Receiving broadcast android.bluetooth.device.action.PAIRING_CANCEL seq=-1 to android.app.ActivityThread$PackageInfo$ReceiverDispatcher@2fd75738
05-07 13:29:18.625: ERROR/ActivityThread(1370): start dispatch OnReceive message,mRegistered=true mCurOrdered=false intent=Intent { act=android.bluetooth.device.action.PAIRING_CANCEL } receiver = com.android.settings.bluetooth.BluetoothEventRedirector$1@2fd74d98
05-07 13:29:18.625: VERBOSE/BluetoothEventRedirector(1370): Received android.bluetooth.device.action.PAIRING_CANCEL
05-07 13:29:18.625: ERROR/xubo(1370): mBroadcastReceiver receive msg = android.bluetooth.device.action.PAIRING_CANCEL
05-07 13:29:18.625: ERROR/ActivityThread(1370): exit dispatch OnReceive message,mRegistered=true mCurOrdered=false

The client has informed that the 'pairing code' is 1234. However, my android phone pairs fine with the device without specifying this. I've verified as such by entering Bluetooth settings, and indeed the device is reported as paired.

Can anyone suggest what's going wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

私藏温柔 2024-11-12 19:20:35

该死,我正要发布答案,我看到你已经修复了它:)

关键在于这一行:

05-07 13:29:18.595: DEBUG/bluez/src/device.c(8031): /org/bluez/8031/hci0/dev_00_06_66_05_70_E7: canceling authentication request

这表明蓝牙配对需要发生,但没有发生。

Darn, I was just about to post an answer and I see you had fixed it :)

The key was in this line:

05-07 13:29:18.595: DEBUG/bluez/src/device.c(8031): /org/bluez/8031/hci0/dev_00_06_66_05_70_E7: canceling authentication request

Which indicates that Bluetooth pairing needed to happen, but didn't take place.

数理化全能战士 2024-11-12 19:20:35

结果发现问题出在未输入配对代码(废话!)。我以编程方式与设备配对,该设备没有请求任何配对代码输入,因此配对不正确。

修复方法是输入 Settings ->无线与网络->蓝牙设置,长按“已配对”设备并选择取消配对,然后单击产生带有文本字段的蓝牙配对请求窗口的设备,进入我输入了 PIN(配对码)。

完成后,配对成功,上面的代码完美运行。

So it turned out the issue was with the pairing code not being entered (duh!). I had programmatically paired with the device, which did not request any pairing code input, thus the pairing was improper.

The fix was to enter Settings -> Wireless & networks -> Bluetooth settings, long press on the "paired" device and select Unpair, then single press on the device which produced a Bluetooth pairing request window with textfield, into which I typed the PIN (pairing code).

After this was done, pairing was successful and the above code worked perfectly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文