简体   繁体   English

Android BluetoothSocket无法连接

[英]Android BluetoothSocket can't connect

I'm doing some stuff with bluetooth on android and I would like to connect to one of the discovered devices and open a socket connection towards it. 我正在用android上的蓝牙做一些事情,我想连接到发现的设备之一,并向它打开套接字连接。

I've granted all of the needed permissions: Bluetooth, Bluetooth_Admin, Access_Fine_Location and Access_Coarse_Location and ask for them before I do anything with bluetooth. 我已授予所有必需的权限:Bluetooth,Bluetooth_Admin,Access_Fine_Location和Access_Coarse_Location,并在我对蓝牙进行任何操作之前先询问它们。

Now, I've discovered some devices with adapter.startDiscovery(); 现在,我发现了一些带有adapter.startDiscovery();设备adapter.startDiscovery(); and activity.registerReceiver(receiver, filter); activity.registerReceiver(receiver, filter);

In the receiver finds a device of a certain name, I try connecting to it like this: 在接收器中找到某个名称的设备,我尝试像这样连接到该设备:

            adapter.cancelDiscovery();
            Log.d(TAG, "Create Bond");
            device.createBond();
            try {
                socket = device.createRfcommSocketToServiceRecord(uuid);
                Log.d(TAG, "Sleep 10");
                sleep(10000);
                Log.d(TAG, "Create Socket");
                //socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                Log.d(TAG, "Connect socket");
                socket.connect();
                Log.d(TAG, "Connecting Done");
            } catch (Exception e) {
                Log.d(TAG, "Failed to connect to device", e);
                try {
                    socket.close();
                } catch (Exception e2) {
                    Log.d(TAG, "Failed to close socket", e2);
                }
            }

This is a test code with which I'm trying to create a socket and open a connection. 这是一个测试代码,我正在尝试使用该代码创建一个套接字并打开一个连接。

I get the following Exception on .connect(): 我在.connect()上收到以下异常:

java.io.IOException: read failed, socket might closed or timeout, read ret: -1 at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:684) at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:696) at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:373) java.io.IOException:读取失败,套接字可能关闭或超时,读取ret:android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:684)-1在android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:696)在android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:373)

What am I doing wrong. 我究竟做错了什么。

The bluetooth device I connect to is a Android mobile device, but I plan on using others when I manage to get the connection. 我连接的蓝牙设备是Android移动设备,但是我计划在设法获得连接时使用其他设备。

Update1: Android version is 7.0 Update1:​​Android版本为7.0

使用fetchUuidsWithSdp()getUuids()查找所有已发布的服务及其关联的UUID值。

You don't need to call device.createBond(); 您不需要调用device.createBond(); to connect to a Bluetooth device. 连接到蓝牙设备。

Try removing this line. 尝试删除此行。 Also check, that your phone is not already paired with the device you're trying to connect to. 另外,请检查您的手机是否尚未与您要连接的设备配对。 You can check that on the Bluetooth settings screen (open it with a long press on the Bluetooth icon on your smartphone. 您可以在“蓝牙设置”屏幕上进行检查(长按智能手机上的“蓝牙”图标将其打开。

Here is a sample code to initiates a Bluetooth connection : 这是启动蓝牙连接的示例代码:

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

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket
        // because mmSocket is final.
        BluetoothSocket tmp = null;
        mmDevice = device;

        try {
            // Get a BluetoothSocket to connect with the given BluetoothDevice.
            // MY_UUID is the app's UUID string, also used in the server code.
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Log.e(TAG, "Socket's create() method failed", e);
        }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it otherwise slows down the connection.
        bluetoothAdapter.cancelDiscovery();

        try {
            // Connect to the remote device through the socket. This call blocks
            // until it succeeds or throws an exception.
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and return.
            try {
                mmSocket.close();
            } catch (IOException closeException) {
                Log.e(TAG, "Could not close the client socket", closeException);
            }
            return;
        }

        // The connection attempt succeeded. Perform work associated with
        // the connection in a separate thread.
        manageMyConnectedSocket(mmSocket);
    }

    // Closes the client socket and causes the thread to finish.
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "Could not close the client socket", e);
        }
    }
}

This code is from Android official doc: https://developer.android.com/guide/topics/connectivity/bluetooth#ConnectAsAClient 该代码来自Android官方文档: https//developer.android.com/guide/topics/connectivity/bluetooth#ConnectAsAClient

I wrote another code instead of what I was using for server side. 我写了另一个代码,而不是我在服务器端使用的代码。

            Log.d(TAG,"Start server");
            BluetoothServerSocket serverSocket = null;
            try {
                serverSocket = adapter.listenUsingRfcommWithServiceRecord("ime", uuid);
            } catch (Exception e) {
                e.printStackTrace();
            }

            while (true) {
                try {
                    serverSocket.accept();
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

I used this code inside of a thread which starts instead of calling the code from the question. 我在启动线程的内部使用了此代码,而不是从问题中调用代码。

Installing the App with server code on one app and calling "connect" on socket did the trick. 在一个应用程序上使用服务器代码安装该应用程序并在套接字上调用“ connect”就可以了。 I used the same UUID (previous was random generated, new one was static from string). 我使用了相同的UUID(上一个是随机生成的,新的是从字符串中静态生成的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM