无法在android studio中使用带插座的蓝牙设备连接

时间:2017-10-12 11:15:19

标签: android bluetooth client

大家好,我是Android开发人员的新手,我将蓝牙设备作为不同类线程的客户端进行连接。如果发生Nullpointerexcception,那么我使用默认的UUID。在此之后,当我使用socket.connect()时,它会显示调试警告,并且不会向设备发送任何配对请求。什么都没发生。如果任何人可以提供帮助,我是Android开发的新手。提前谢谢。

警告和日志

Warning and Logs

这是我在Thread中的代码;

class ConnectWithDevice(context : ConnectWithBluetooth, device : BluetoothDevice) : Thread(){

    private val mContext : ConnectWithBluetooth = context
    private val mmSocket : BluetoothSocket
    private val mmDevice : BluetoothDevice
    // Default UUID
    private val mmDefaultUUID = UUID.fromString("78c374fd-f84d-4a9e-aa5b-9b0b6292952e")

    init {
        var temp : BluetoothSocket? = null
        mmDevice = device
        try {
            temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)
        }catch (en : NullPointerException){
            en.printStackTrace()               
            temp = device.createRfcommSocketToServiceRecord(mmDefaultUUID)
        }catch (e : IOException){
            e.printStackTrace()
            Log.e("TAG","Socket's create() method failed",e)
        }
        mmSocket = temp!!
        Log.i("TAG","Got the Socket")
    }

    override fun run() {
        // Cancel discovery because it otherwise slows down the connection.
        if(mContext.bluetoothAdapter != null){
            mContext.bluetoothAdapter!!.cancelDiscovery()
        }

        try{
            // Connect to the remote device through the socket. This call blocks
            // until it succeeds or throws an exception.
            Log.i("TAG","Connecting...")
            mmSocket.connect()
            Log.i("TAG","Bluetooth Successfully Connected")
        }catch (connectException : IOException){
            // Unable to connect; close the socket and return.
            try{
                mmSocket.close()
            }catch (closeException : IOException){
                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.
        Log.i("TAG","Device is Connected")
        //manageMyConnectedSocket(mmSocket)
    }

    // Closes the client socket and causes the thread to finish.
    // Call this method from the main activity to shut down the connection.
    fun cancel(){
        try {
            mmSocket.close()
        } catch (e: IOException) {
            Log.e(ContentValues.TAG, "Could not close the client socket", e)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

最后我在这里找到解决方案 - > 我使用此代码 - >

val m = device.javaClass.getMethod("createRfcommSocket", *arrayOf<Class<*>>(Int::class.java))
            temp = m.invoke(device, 1) as BluetoothSocket

而不是这个 - &gt;

temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)