Android 10 - Ошибка подключения Bluetooth - java .io.IOException: чтение не удалось, сокет может быть закрыт или истекло время ожидания, чтение: -1 - PullRequest
0 голосов
/ 02 мая 2020

Я пытаюсь подключить два телефона Android через Bluetooth. Тем не менее, я могу получить парное окно на моем телефоне при использовании device.createBond(), но не bluetoothSocket.connect() Вот мой код.

class Bluetooth(private val bluetoothAdapter: BluetoothAdapter, private val context: Context) {
    private lateinit var bluetoothSocket: BluetoothSocket
    private val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
    val bluetoothReceiver = BluetoothReceiver()
    var isFound = false
    var isRunning = true

    fun connect(device: BluetoothDevice) {
        if (bluetoothAdapter.isDiscovering) {
            bluetoothAdapter.cancelDiscovery()
        }
        context.unregisterReceiver(bluetoothReceiver)
        bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid)
        bluetoothSocket.connect()
    }

    fun search() {
        if (bluetoothAdapter.isDiscovering) {
            bluetoothAdapter.cancelDiscovery()
        }
        val pairedDevices = bluetoothAdapter.bondedDevices
        for (device in pairedDevices) {
            if (device.name == "Target Bluetooth Name") {
                isFound = true
                connect(device)
                break
            }
        }

        if (!isFound) {
            context.registerReceiver(bluetoothReceiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
            context.registerReceiver(bluetoothReceiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
            bluetoothAdapter.startDiscovery()
            Toast.makeText(context, "Searching... Please wait...", Toast.LENGTH_SHORT).show()
        }
    }

    inner class BluetoothReceiver : BroadcastReceiver() {
        override fun onReceive(mContext: Context, intent: Intent) {
            val action = intent.action
            if (BluetoothDevice.ACTION_FOUND == action) {
                val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                if (device != null && device.bondState != BluetoothDevice.BOND_BONDED) {
                    if (device.name == "Target Bluetooth Name") {
                        isFound = true
                        connect(device)
                    }
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
                bluetoothAdapter.cancelDiscovery()
                context.unregisterReceiver(bluetoothReceiver)
                isRunning = false
                if (!isFound) {
                    Toast.makeText(context, "Nothing found", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}

Когда я использую bluetooth = Bluetooth(BluetoothAdapter.getDefaultAdapter(), this) и bluetoorh.search() в MainActivity.kt

Приложение взломает sh при обнаружении Bluetooth с именем Целевое имя Bluetooth .

Как это исправить? Пожалуйста, порекомендуйте. Спасибо.

2020-05-02 19:07:09.640 3245-3245/com.example.bluetooth E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.bluetooth, PID: 3245
    java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 pkg=com.example.bluetooth (has extras) } in com.example.bluetooth.Bluetooth$BluetoothReceiver@f0639f0
        at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1560)
        at android.app.-$$Lambda$LoadedApk$ReceiverDispatcher$Args$_BumDX2UKsnxLVrE6UJsJZkotuA.run(Unknown Source:2)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: 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.readInt(BluetoothSocket.java:786)
        at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:404)
        at com.example.bluetooth.Bluetooth.connect(Bluetooth.kt:37)
        at com.example.bluetooth.Bluetooth$BluetoothReceiver.onReceive(Bluetooth.kt:112)
        at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1550)
        at android.app.-$$Lambda$LoadedApk$ReceiverDispatcher$Args$_BumDX2UKsnxLVrE6UJsJZkotuA.run(Unknown Source:2) 
        at android.os.Handler.handleCallback(Handler.java:883) 
        at android.os.Handler.dispatchMessage(Handler.java:100) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 

Bluetooth pairing request

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...