Android:如何断开已连接的蓝牙设备?

时间:2020-07-12 07:11:08

标签: android kotlin bluetooth

我具有连接功能,并且效果很好

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

但是bts.close()不起作用,如果我叫这个

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

1 个答案:

答案 0 :(得分:0)

科特林

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)
}