简体   繁体   中英

Android : How to disconnect already connected bluetooth device?

I have connect function and it works perfect

    fun connect(btDevice: BluetoothDevice?) {
        val id: UUID = btDevice?.uuids?.get(0)!!.uuid
        val bts = btDevice.createInsecureRfcommSocketToServiceRecord(id)
        bts?.connect()
    }

But bts.close() doesnt`t works, if i call this one

D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@518c676, channel: 2, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@d48a477, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@51478e4mSocket: null, mSocketState: CLOSED

Kotlin

private fun disconnect(device: BluetoothDevice) {
    val serviceListener: BluetoothProfile.ServiceListener = object :
        BluetoothProfile.ServiceListener {
        override fun onServiceDisconnected(profile: Int) {}

        @SuppressLint("DiscouragedPrivateApi")
        override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
            val disconnect = BluetoothA2dp::class.java.getDeclaredMethod(
                "disconnect",
                BluetoothDevice::class.java
            )
            disconnect.isAccessible = true
            disconnect.invoke(proxy, device)
            BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy)
        }
    }
    BluetoothAdapter.getDefaultAdapter()
        .getProfileProxy(this, serviceListener, BluetoothProfile.A2DP)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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