Android 蓝牙服务在设备之间传输数据

发布于 2025-01-12 07:42:35 字数 6280 浏览 1 评论 0原文

你好,我是 Android 开发新手,我正在阅读有关 android 蓝牙的内容 这里是有关 Android 开发的内容文档。 我能够设置蓝牙、找到绑定设备并进行连接,但在它们之间传输数据时遇到问题 这是监听蓝牙连接请求的蓝牙服务器套接字代码。

class BluetoothActivity : AppCompatActivity() {
private lateinit var listen: Button
private lateinit var msgBox:TextView
private lateinit var status:TextView
private lateinit var sendButton: Button
private lateinit var writeMsg:EditText
private lateinit var listDevice:Button
private lateinit var listView: ListView
private val handler = Handler()
private var bluetoothDevices = arrayListOf<BluetoothDevice>()
private var deviceName = arrayListOf<String>()


private inner class ServerAcceptThread:Thread(){
    private val mmServerSocket:BluetoothServerSocket? by lazy(LazyThreadSafetyMode.NONE){
        bluetoothAdapter?.listenUsingInsecureRfcommWithServiceRecord(myName,myUUID)
    }

    override fun run() {
        //Keep listen until error occured or socket is returned
        var shouldKeepListen = true

        while (shouldKeepListen){
            val socket:BluetoothSocket? = try {
                mmServerSocket?.accept()
            }catch (e:IOException){
                Log.e("bluetoothSocket","ServerSocket failde",e)
                shouldKeepListen = false
                null
            }
            if (socket!= null){
                val connected = ConnectedThread(socket)
                connected.start()
            }
        }
    }

    //Close server socket and cause the thread to finish
    fun cancel(){
        try {
            mmServerSocket?.close()
        }catch (e:IOException){
            Log.e("ConnectionFailed!", "Connection close failed",e)
        }
    }
}

下面是连接到蓝牙服务器套接字的蓝牙客户端的代码。

private inner class ClientConnectThread(device: BluetoothDevice):Thread(){
    private val mmSocket:BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE){
        device.createRfcommSocketToServiceRecord(myUUID)
    }

    public override fun run() {
        //Cancel the discovery process because it slow down the connection
        bluetoothAdapter?.cancelDiscovery()

        mmSocket?.let { socket ->
            socket.connect()
        }
    }

    fun cancel(){
        try {
            mmSocket?.close()
        }catch (e:IOException){
            Log.e("Socket", "Could not close the client socket",e)
        }
    }
}

然后我有蓝牙服务,可以读取和写入数据以发送到远程设备(客户端)。它以BluetoothSocket作为参数,服务器正在监听

    private inner class ConnectedThread(private val mmSocket:BluetoothSocket):Thread(){
        private val mmInPutStream:InputStream = mmSocket.inputStream
        private val mmOutPutStream:OutputStream = mmSocket.outputStream
        private val mmBuffer:ByteArray = ByteArray(1024)

        override fun run() {
            var numByte:Int //number of bytes returns from read()

            //keep listen to the InputStream until an error occured
            while (true){
                //Read from inputStream
                numByte = try {
                    mmInPutStream.read(mmBuffer)
                }catch (e:IOException){
                    Log.e(TAG,"InputStream was disconnected",e)
                    break
                }
                //Send the message to Ui activity
                val readMsg = handler.obtainMessage(
                    MESSAGE_READ,numByte,-1,mmBuffer
                )
                readMsg.sendToTarget()
            }
        }

        //Call this function to mainActivity to send data to remote device
        fun write(byte:ByteArray){
            try {
                mmOutPutStream.write(byte)
            }catch (e:IOException){
                Log.e(TAG,"Error occured during send messge",e)

                //Send the failed message back to activity
                val writeErrorMessage = handler.obtainMessage(MESSAGE_TOAST)
                val bundle = Bundle().apply {
                    putString("Toast","could not send the data")
                }
                writeErrorMessage.data = bundle
                handler.sendMessage(writeErrorMessage)
                return
            }

            //Share the sent message with UI activity
            val writtenMsg = handler.obtainMessage(
                MESSAGE_WRITE, -1,-1,mmBuffer
            )
            writtenMsg.sendToTarget()
        }

        //Call this method to activity to shut socket
        fun cancle(){
            try {
                mmSocket.close()
            }catch (e:IOException){
                Log.e(TAG,"Connection closed failed!")
            }
        }
    }
}

,我还实现了UI的监听器来开始监听连接请求,列出绑定设备并连接到远程设备并通过彼此传输数据。

fun implementsListeners(){
    listDevice.setOnClickListener {
        val pairedDevice: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices
        var index:Int = 0
        val pairedDevice: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices
        if (pairedDevice != null){
            var listDeviceName = arrayListOf<String>()
            try {
                pairedDevice.forEachIndexed { index, device ->
                    listDeviceName.add(index, device.name)
                    bluetoothDevices.add(device)
                }
            }catch (e:IndexOutOfBoundsException){
                Log.e(TAG, "indexOutOfBond",e)
            }
            val arrayAdapter:ArrayAdapter<String> = ArrayAdapter(
                this,android.R.layout.simple_list_item_1,listDeviceName
            )
            listView.adapter =arrayAdapter
    }

    listen.setOnClickListener {
       val serverClass = ServerAcceptThread()
        serverClass.start()
    }

    listView.setOnItemClickListener { parent, view, position, id ->
        val client = ClientConnectThread(bluetoothDevices[position])
        client.start()
        status.text = "Connecting..."

    }

    sendButton.setOnClickListener {
        val client = BluetoothService(Handler())
        //Call the write() method to write data

    }

我的问题是如何访问 ConnectedThread 上的 write() 方法和 read() 方法。我尝试实例化 ConnectedThread,但它采用 BluetoothSocket 作为参数,我无法访问客户端或服务器类之外的套接字。方法任何帮助或建议。我会很感激

Hello am new in Android development I was reading about android bluetooth Here on Android development documentation.
I was able to setup bluetooth, find the bonded device and to connect but am having an issue on transfer data between them
Here is the bluetooth server socket code that listen to bluetooth connection request.

class BluetoothActivity : AppCompatActivity() {
private lateinit var listen: Button
private lateinit var msgBox:TextView
private lateinit var status:TextView
private lateinit var sendButton: Button
private lateinit var writeMsg:EditText
private lateinit var listDevice:Button
private lateinit var listView: ListView
private val handler = Handler()
private var bluetoothDevices = arrayListOf<BluetoothDevice>()
private var deviceName = arrayListOf<String>()


private inner class ServerAcceptThread:Thread(){
    private val mmServerSocket:BluetoothServerSocket? by lazy(LazyThreadSafetyMode.NONE){
        bluetoothAdapter?.listenUsingInsecureRfcommWithServiceRecord(myName,myUUID)
    }

    override fun run() {
        //Keep listen until error occured or socket is returned
        var shouldKeepListen = true

        while (shouldKeepListen){
            val socket:BluetoothSocket? = try {
                mmServerSocket?.accept()
            }catch (e:IOException){
                Log.e("bluetoothSocket","ServerSocket failde",e)
                shouldKeepListen = false
                null
            }
            if (socket!= null){
                val connected = ConnectedThread(socket)
                connected.start()
            }
        }
    }

    //Close server socket and cause the thread to finish
    fun cancel(){
        try {
            mmServerSocket?.close()
        }catch (e:IOException){
            Log.e("ConnectionFailed!", "Connection close failed",e)
        }
    }
}

And down below is the code for Bluetooth client that connect to bluetooth server socket.

private inner class ClientConnectThread(device: BluetoothDevice):Thread(){
    private val mmSocket:BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE){
        device.createRfcommSocketToServiceRecord(myUUID)
    }

    public override fun run() {
        //Cancel the discovery process because it slow down the connection
        bluetoothAdapter?.cancelDiscovery()

        mmSocket?.let { socket ->
            socket.connect()
        }
    }

    fun cancel(){
        try {
            mmSocket?.close()
        }catch (e:IOException){
            Log.e("Socket", "Could not close the client socket",e)
        }
    }
}

And Then I have bluetooth service that read and write data to send to remote device (client). which take BluetoothSocket as parameter, were the server is listening to

    private inner class ConnectedThread(private val mmSocket:BluetoothSocket):Thread(){
        private val mmInPutStream:InputStream = mmSocket.inputStream
        private val mmOutPutStream:OutputStream = mmSocket.outputStream
        private val mmBuffer:ByteArray = ByteArray(1024)

        override fun run() {
            var numByte:Int //number of bytes returns from read()

            //keep listen to the InputStream until an error occured
            while (true){
                //Read from inputStream
                numByte = try {
                    mmInPutStream.read(mmBuffer)
                }catch (e:IOException){
                    Log.e(TAG,"InputStream was disconnected",e)
                    break
                }
                //Send the message to Ui activity
                val readMsg = handler.obtainMessage(
                    MESSAGE_READ,numByte,-1,mmBuffer
                )
                readMsg.sendToTarget()
            }
        }

        //Call this function to mainActivity to send data to remote device
        fun write(byte:ByteArray){
            try {
                mmOutPutStream.write(byte)
            }catch (e:IOException){
                Log.e(TAG,"Error occured during send messge",e)

                //Send the failed message back to activity
                val writeErrorMessage = handler.obtainMessage(MESSAGE_TOAST)
                val bundle = Bundle().apply {
                    putString("Toast","could not send the data")
                }
                writeErrorMessage.data = bundle
                handler.sendMessage(writeErrorMessage)
                return
            }

            //Share the sent message with UI activity
            val writtenMsg = handler.obtainMessage(
                MESSAGE_WRITE, -1,-1,mmBuffer
            )
            writtenMsg.sendToTarget()
        }

        //Call this method to activity to shut socket
        fun cancle(){
            try {
                mmSocket.close()
            }catch (e:IOException){
                Log.e(TAG,"Connection closed failed!")
            }
        }
    }
}

And I have also implement the listener for UI to start listen to a connection request, list Bonded device and connect to remote device and transfer data through each other.

fun implementsListeners(){
    listDevice.setOnClickListener {
        val pairedDevice: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices
        var index:Int = 0
        val pairedDevice: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices
        if (pairedDevice != null){
            var listDeviceName = arrayListOf<String>()
            try {
                pairedDevice.forEachIndexed { index, device ->
                    listDeviceName.add(index, device.name)
                    bluetoothDevices.add(device)
                }
            }catch (e:IndexOutOfBoundsException){
                Log.e(TAG, "indexOutOfBond",e)
            }
            val arrayAdapter:ArrayAdapter<String> = ArrayAdapter(
                this,android.R.layout.simple_list_item_1,listDeviceName
            )
            listView.adapter =arrayAdapter
    }

    listen.setOnClickListener {
       val serverClass = ServerAcceptThread()
        serverClass.start()
    }

    listView.setOnItemClickListener { parent, view, position, id ->
        val client = ClientConnectThread(bluetoothDevices[position])
        client.start()
        status.text = "Connecting..."

    }

    sendButton.setOnClickListener {
        val client = BluetoothService(Handler())
        //Call the write() method to write data

    }

My Question is how can I access the write() method and read() that is on ConnectedThread. I have tried to Instantiate ConnectedThread but it's take BluetoothSocket as parameter I can't access the socket outside client or server class. Method Any help or suggestion on. I would Appreciate

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文