ANDROID BLUETOOTH CLASSIC – PART 4

by phongpn3
99 views

Chào các bạn, hôm nay mình tiếp tục chuỗi bài liên quan đến Bluetooth Classic trong Android. Bài hôm nay mình tập trung vào phần Transfer Bluetooth Data.

Sau khi bạn đã kết nối thành công với thiết bị Bluetooth, mỗi thiết bị có một BluetoothSocket được kết nối. Sau đó bạn có thể chia sẻ thông tin giữa các thiết bị bằng cách thông qua đối tượng BluetoothSocket, về cơ bản các bước đọc ghi dữ, để truyền dữ liệu như sau:

  • Get InputStream và OutputStream xử lý truyền qua Socket bằng cách sử dụng getInputStream() và getOutputStream() tương ứng.
  • Đọc và ghi dữ liệu vào các luồng sử dụng read(byte[]) và write(byte[]).

Mình sẽ tạo một ví dụ minh hoạ, với ứng dụng Chat giữa client và server bằng Bluetooth Classic.

Đầu tiên chúng ta tạo một Object chứa phương thức đọc, ghi. Xử lý Read, Write thông qua 2 object InputStream và OutputStream.

private val bluetoothAdapter: BluetoothAdapter = adapter
private val handler: Handler = mHandler

private lateinit var bluetoothSending: BluetoothSending
inner class BluetoothSending(bluetoothSocket: BluetoothSocket?) : Thread() {

    private val inputStream: InputStream?
    private val outputStream: OutputStream?

    init {
        var tempIn: InputStream? = null
        var tempOut: OutputStream? = null
        try {
            tempIn = bluetoothSocket?.inputStream
            tempOut = bluetoothSocket?.outputStream
        } catch (e: IOException) {
            e.printStackTrace()
        }
        inputStream = tempIn
        outputStream = tempOut
    }

    override fun run() {
        val buffer = ByteArray(1024)
        var bytes: Int

        // Keep listening to the InputStream until an exception occurs.
        while (true) {
            try {
                bytes = inputStream?.read(buffer)!!
                handler.obtainMessage(Contstants.STATE_MESSAGE_RECEIVED, bytes, -1, buffer)
                    .sendToTarget()
            } catch (e: IOException) {
                Log.e("PhongPN", "Bluetooth Reading Data Error", e)
                e.printStackTrace()
            }
        }
    }

    fun write(bytes: ByteArray?) {
        try {
            outputStream?.write(bytes)
        } catch (e: IOException) {
            Log.e("PhongPN", "Bluetooth Writing Data Error", e)
            e.printStackTrace()
        }
    }
}

Tiếp đến chúng ta tạo một Server Socket. Lắng nghe các kết nối đến nó.

inner class ServerClass : Thread() {

    private var serverSocket: BluetoothServerSocket? = null

    init {
        try {
            serverSocket =
                bluetoothAdapter.listenUsingRfcommWithServiceRecord(
                    "PhongPN Transfer Data Bluetooth Classic", UUID.fromString(
                        Contstants.UUID
                    )
                )
        } catch (e: IOException) {
            Log.e("PhongPN", "Could not listen RFCOMM Sockets", e)
            e.printStackTrace()
        }
    }

    override fun run() {
        var socket: BluetoothSocket? = null
        while (socket == null) {
            try {
                val message = Message.obtain()
                message.what = Contstants.STATE_CONNECTING
                handler.sendMessage(message)
                socket = serverSocket?.accept()
            } catch (e: IOException) {
                e.printStackTrace()
                val message = Message.obtain()
                message.what = Contstants.STATE_CONNECTION_FAILED
                handler.sendMessage(message)
            }
            if (socket != null) {
                val message = Message.obtain()
                message.what = Contstants.STATE_CONNECTED
                handler.sendMessage(message)
                bluetoothSending = BluetoothSending(socket)
                bluetoothSending.start()
                break
            }
        }
    }

    fun cancel() {
        try {
            serverSocket?.close()
        } catch (e: IOException) {
            Log.e("PhongPN", "Could not close the connect socket", e)
            e.printStackTrace()
        }
    }
}

Cuối cùng, chúng ta tạo một Client tương tác và trao đổi dữ liệu với Server Socket.

inner class ClientClass(device: BluetoothDevice) : Thread() {

    private var socket: BluetoothSocket? = null

    init {
        try {
            socket = device.createRfcommSocketToServiceRecord(UUID.fromString(Contstants.UUID))
        } catch (e: IOException) {
            Log.e("PhongPN", "Could not create RFCOMM Sockets", e)
            e.printStackTrace()
        }
    }

    override fun run() {
        try {
            socket?.connect()
            val message = Message.obtain()
            message.what = Contstants.STATE_CONNECTED
            handler.sendMessage(message)
            bluetoothSending = BluetoothSending(socket)
            bluetoothSending.start()
        } catch (e: IOException) {
            e.printStackTrace()
            val message = Message.obtain()
            message.what = Contstants.STATE_CONNECTION_FAILED
            handler.sendMessage(message)
        }
    }

    fun cancel() {
        try {
            socket?.close()
        } catch (e: IOException) {
            Log.e("PhongPN", "Could not close the connect socket", e)
            e.printStackTrace()
        }
    }
}

Chúng ta xử lý send data tới nơi hiển thị dữ liệu (View) qua đối tượng Handle.

private val handler: Handler = object : Handler(Looper.getMainLooper()) {
    override fun handleMessage(message: Message) {
        when (message.what) {
            Contstants.STATE_LISTENING -> binding.txtStatus.text = "Listening"
            Contstants.STATE_CONNECTING -> binding.txtStatus.text = "Connecting"
            Contstants.STATE_CONNECTED -> binding.txtStatus.text = "Connected"
            Contstants.STATE_CONNECTION_FAILED -> binding.txtStatus.text = "Connection Failed"
            Contstants.STATE_MESSAGE_RECEIVED -> {
                val readBuff = message.obj as ByteArray
                val tempMsg = String(readBuff, 0, message.arg1)
                binding.txtReceivedMessage.text = tempMsg
            }
        }
    }
}

Các bạn chú ý là phương thức close() của luồng cho phép bạn chấm dứt kết nối bất kỳ lúc nào bằng cách đóng BluetoothSocket. Các nên gọi phương thức này khi bạn sử dụng xong kết nối Bluetooth. Vì thế trong 2 class client vs server mình luôn có 2 hàm đó để sẵn sàng trong việc đóng kết nối.

Trên đây là chuỗi bài viết của mình liên quan đến Bluetooth Classic trong Android. Mong đâu đấy chút chia sẻ của mình có thế giúp mọi người có cái nhìn sơ qua về Bluetooth Classic, cũng như là có thể ít nhiều giúp các bạn nếu có gặp phải bài toán liên quan đến nó trong tương lai.

Cảm ơn mọi người đã theo dõi. Hẹn gặp lại trong các bài viết sắp tới.

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.