蓝牙连接失败:读取失败,套接字可能关闭或超时,读取ret:-1

时间:2016-04-22 05:57:20

标签: java android bluetooth

我正在尝试创建蓝牙连接

我可以搜索附近的设备,但是当我尝试连接时,我得到一个我不明白的错误:

的logcat

01-03 00:55:06.909 6654-6654/com.bluetooth.prova3.listdiscovery D/CONNECTTHREAD: Could not close connection:java.io.IOException: read failed, socket might closed or timeout, read ret: -1

我有两个连接类,一个接收设备并执行连接,另一个用于连接。

ConexionActivity.Java

package com.bluetooth.prova3.listdiscovery;

***Imports*****

public class ConexionActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conexion);

        //Aqui rebo el dispositiu que he seleccionat per conectarme
        Intent intent = getIntent();
        BluetoothDevice bluetoothDevice = intent.getExtras().getParcelable("btdevice");
        //mostro el nom per la pantalla amb un text view
        TextView MacAddress = (TextView)findViewById(R.id.MAC);
        String aaaa = bluetoothDevice.getName() + "\n" + bluetoothDevice.getAddress();
        MacAddress.setText(aaaa);

        ConnectThread conexion = new ConnectThread(bluetoothDevice);
        conexion.run();
    }
}

ConnectThread.java

package com.bluetooth.prova3.listdiscovery;

导入

public class ConnectThread extends Thread{
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    UUID UUIDaleatorio = UUID.randomUUID();
    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(UUIDaleatorio);
        } catch (IOException e) {

            Log.d("CONNECTTHREAD", "Could not close connection:" + e.toString());
        }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        //mBluetoothAdapter.cancelDiscovery();
       try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException connectException) {
           Log.d("CONNECTTHREAD", "Could not close connection:" + connectException.toString());
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { Log.d("CONNECTTHREAD", "Could not close connection:" + closeException.toString());}
            return;
        }

        // Do work to manage the connection (in a separate thread)
       // manageConnectedSocket(mmSocket);
    }

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

5 个答案:

答案 0 :(得分:11)

尝试使用,

createInsecureRfcommSocketToServiceRecord(MY_UUID)

取代

createRfcommSocketToServiceRecord(MY_UUID)

这应该可以解决问题。如果这不能解决问题,请分享您的调试结果。

此外,请勿生成随机UUID,请尝试以下内容。

UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

答案 1 :(得分:1)

我在帖子中捆绑了所有解决方案,但没有成功。错误依旧出现:

java.io.IOException: read failed, socket might closed or timeout, read ret: -1
            at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:772)
            at android.bluetooth.BluetoothSocket.waitSocketSignal(BluetoothSocket.java:725)
            at android.bluetooth.BluetoothSocket.accept(BluetoothSocket.java:499)
            at android.bluetooth.BluetoothServerSocket.accept(BluetoothServerSocket.java:171)
            at android.bluetooth.BluetoothServerSocket.accept(BluetoothServerSocket.java:157)
            at com.milen.bluetoothapp.services.MyBluetoothService$AcceptThread.run(BluetoothConnectionService.kt:71)

当我更改 createInsecureRfcommSocketToServiceRecord(MY_UUID) 时,我获得了成功:

private inner class ConnectThread(device: BluetoothDevice) : Thread() {
    
        private var bluetoothSocket: BluetoothSocket? = device.javaClass.getMethod(
            "createRfcommSocket", Int::class.javaPrimitiveType
        ).invoke(device, 1) as BluetoothSocket?
...
}

是的,这是一种骇人听闻的反思方式,但它可以挽救某人的生命;)。 在 Java 中,它看起来像这样:

BluetoothSocket tmp = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class } ).invoke(device, 1);

顺便说一下,我在一个开源 Github 项目 here

中找到了解决方案

答案 2 :(得分:0)

这对我有用。

C:\Users\Test\Desktop\xml\xml\User1\User1\user1\Windows\abc
C:\Users\Test\Desktop\xml\xml\User1\User1\user1\Windows1\
C:\Users\Test\Desktop\xml\xml\User2\User2\user2\Windows\
C:\Users\Test\Desktop\xml\xml\User2\User2\user2\Windows1\abc

答案 3 :(得分:0)

始终检查您的设备是否已配对!失败会导致同样的错误。

select 'q
w' as tst, hex('
') as what_is_newline

答案 4 :(得分:0)

我也为此错误挣扎了一段时间。以下是最终对我有用的内容(在 Kotlin 中):

MainActivity.kt:

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Intent
import android.os.Bundle
import android.os.ParcelUuid
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {

    private val requestCode = 101

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        connectBluetooth()
    }

    private fun connectBluetooth() {

        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

        if (!bluetoothAdapter.isEnabled) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBtIntent, requestCode)
        }

        val pairedDevices = bluetoothAdapter.bondedDevices

        if(pairedDevices.isNotEmpty()){
            val device: BluetoothDevice = pairedDevices.first()
            val connectThread = Thread(ConnectThread(device))
            findViewById<TextView>(R.id.textView).text = device.name
            findViewById<Button>(R.id.connectBtn).setOnClickListener{ connectThread.run() }
            findViewById<Button>(R.id.disconnectBtn).setOnClickListener{ connectThread.run() }
        }
    }


    private inner class ConnectThread(device: BluetoothDevice) : Thread() {

        private val uuid: ParcelUuid = ParcelUuid.fromString("0000112f-0000-1000-8000-00805f9b34fb")
        private val mmSocket: BluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid.uuid)

        override fun run() {
            try {
                if(mmSocket.isConnected) mmSocket.close() else mmSocket.connect()
                Log.d("Bluetooth Activity", "Socket is connected: ${mmSocket.isConnected}")
            } catch (ex: Exception) {
                Log.e("Bluetooth Activity", ex.toString())
            }
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No device connected"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/connectBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="48dp"
        android:text="Connect"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/textView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.501" />

    <Button
        android:id="@+id/disconnectBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="64dp"
        android:text="Disconnect"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.498" />

</androidx.constraintlayout.widget.ConstraintLayout>