Bluetooth Chat App Complete Tutorial Kotlin Android Studio

61 Просмотры
Издатель
Bluetooth Chat App Complete Tutorial Kotlin Android Studio
#bluetooth #chatapp #bluetoothadapter #kotlin #java #androidstudio
#androidapp #noobdeveloper

To create a connection between two devices, you must implement both the server-side and client-side mechanisms because one device must open a server socket, and the other one must initiate the connection using the server device's MAC address. The server device and the client device each obtain the required BluetoothSocket in different ways. The server receives socket information when an incoming connection is accepted. The client provides socket information when it opens an RFCOMM channel to the server.
The server and client are considered connected to each other when they each have a connected BluetoothSocket on the same RFCOMM channel. At this point, each device can obtain input and output streams, and data transfer can begin, which is discussed in the section about transferring Bluetooth data. This section describes how to initiate the connection between two devices.
Connect as a server
When you want to connect two devices, one must act as a server by holding an open BluetoothServerSocket. The purpose of the server socket is to listen for incoming connection requests and provide a connected BluetoothSocket after a request is accepted. When the BluetoothSocket is acquired from the BluetoothServerSocket, the BluetoothServerSocket can—and should—be discarded, unless you want the device to accept more connections.
1 = Get a BluetoothServerSocket by calling listenUsingRfcommWithServiceRecord(String, UUID).
2=Start listening for connection requests by calling accept().
3=Unless you want to accept additional connections, call close().

Connect as a client
In order to initiate a connection with a remote device that is accepting connections on an open server socket, you must first obtain a BluetoothDevice object that represents the remote device. To learn how to create a BluetoothDevice, see Find Bluetooth devices. You must then use the BluetoothDevice to acquire a BluetoothSocket and initiate the connection.
1=Using the BluetoothDevice, get a BluetoothSocket by calling createRfcommSocketToServiceRecord(UUID).
2=Initiate the connection by calling connect(). Note that this method is a blocking call.
After you have successfully connected to a Bluetooth device, each one has a connected BluetoothSocket. You can now share information between devices. Using the BluetoothSocket, the general procedure to transfer data is as follows:

Get the InputStream and OutputStream that handle transmissions through the socket using getInputStream() and getOutputStream(), respectively.

Read and write data to the streams using read(byte[]) and write(byte[]).
Категория
Язык программирования Kotlin
Комментариев нет.