The benefits of using Bluetooth cannot be convincing. Today we are going to connect Bluetooth devices and communicate with them. Traditionally we start by adding the necessary permissions to the manifest file.

The first permission gives us the ability to use Bluetooth, the second to turn it on and off (and we have to be able to if the BT is disabled).

 

We will write an application that will be able to:

  • Broadcast your existence so that other devices scanned for equipment with BlueTooth can see us. If devices are not paired, the non-live device will not be visible.
  • View the list of paired devices on the console
  • Detect other detectable devices (ie broadcasting the fact of their existence).
  • Create a BlueTooth-based network server that will expect the client to connect, and when that happens, he will send a message.
  • Connect as a client to another device on which the server will run.
Our application will work both as a client and as a server. This will depend on which button you press. In order to be able to test the application, you will best be equipped with two physical devices equipped with BlueTooth. I stick a couple of buttons that will run the previously discussed functions. On the TextView component, the current text “TextView” will be displayed when the application is launched, the mac address of our device will appear. TextView, which initially displays “Connection not established”, displays application mode later – as a server or as a client. In the edit field, we will enter the MAC address of the device that will work as a server. I put here my phone’s address, so I do not have to say it every time.
 
Let’s now go to the main activity code. At first, the onCreate method lays visual components into objects. Nothing new or extraordinary:
Next, in the onCreate method, I am hooking up calls to methods that implement individual functions into buttons.
Explanations may only require lines 67-69 and 75-78. Depending on whether the application on the device will work as a server or client, the threads that execute the tasks of that page are called. I based this on threads because, for example, waiting for a connection or linking process are operations that would block the main activity thread. In this way, the threads work asynchronously, and the application does not “block”. Object three of line 76 represents the physical Bluetooth adapter of the device. Line 77 is to retrieve the mac address entered in the edit field. This will be the address we need, after passing it through the constructor parameter to the client thread. He must know what is the address of the device to connect to. In lines 68 and 75, depending on the mode of operation of the application, I display in the corresponding field on the screen,
Let’s move on. Lines 85.86 is the display of the device’s MAC address on the screen and the console. Later in the onCreate activity (lines 87-91) handles the situation if it turns out that the BlueTooth on the device is off. BT verifies the isEnabled () BluetoothAdapter class (line 87). If it turns out to be off, I’ll see a message asking permission to turn BT on. Since I requested the request with startActivityForResult, I also added an onActivityResult method that is automatically invoked by the system when the user agrees to enable BT (or not: p). If the user agrees, the system will start BT and we will only be initializing the object we will use to communicate with the BT physical adapter and possibly display information on the console.
For now, let’s jump to the definition of a BroadcastReceiver object, we’ll be back in a moment, and for now, we’ll look at methods at the end of the class.
This method gives the device a visibility for other devices that scan for “colleagues”.:) If this is not the case, and the devices will not be paired, ours will not be visible to others. Lines 121 and 123 are responsible for displaying the request for “disclosure” and to start broadcasting their existence. Line 122 is an optional setup for broadcast time. By default, the device will broadcast for 2 minutes, while I will give it 300 (seconds) so that it will be visible for 5 minutes.
Method to detectOther () will start searching for other devices. It takes about 12 seconds. Significantly – only those devices that will broadcast their existence will be visible. When a device is found, it will need to handle this event without interrupting the search. For this reason, we record the recipient of a broadcast message informing them of finding a device (line 130). A recipient is a BroadcastReceiver object whose onReceive method is automatically invoked when a device with broadcasting is enabled. Within this method, I extract the object representing the physical device, check if the device has been paired and display information about it.
The operation of these two elements is combined in such a way that the method detectsOther () starts the search for other devices, and when it finds one it is automatically called the onReceive method of the BroadcastReceiver object registered as the recipient of the event. All in all, the console will display information about available devices. When running on the console, I see the device found (if detected, more will appear  ;)):
Within this class we still have the method shown ():
Its task is to check the list of devices that have previously paired and display information about them on the screen. This method does not check whether these devices are available, but only displays information about registered devices that are stored in the system:
For my phone, the Bluetooth headset I’m using (so it has to be paired), and a tablet that had to be paired to BT after my phone calls for the purposes of this article.
Now let’s move on to the communication element. If you have ever programmed client-server network connections in Java, you will definitely recognize multiple components. Basically it is a simple socket connection with the difference that our communication will not be on the network and Bluetooth. First, we will take a class for the application as a server.
In line 15, I define the socket that will be used to communicate. The lines 21 and 22 may be skewed. The service must have a unique identifier, which will be uniquely identified ( http://en.wikipedia.org/wiki/Universally_unique_identifier ). In these lines, our service is registered under the name “Welcome service” under the ID
550e8400-e29b-41d4-a716-446655440000
This is just an accidental ID, I copied an example of such an ID from the internet. Lines 27-54 is a classic implementation of the listening process, the difference is that no network and bluetooth. The thread waits for a contact from the server, then opens the stream and sends the text “Hello friend!”.
Client side:
On this page I open the socket for connection to the server (similar to the server side not the network socket and after the bluetooth) and read what the server sent me.
I run the program on both devices, the phone is doing the server, the tablet behind the client.
Server performance:
On the client side:
If you would like to develop this program or write something on its own, remember that we are dealing with a slightly different network protocol and the BT service on one side can only connect to one other service.