Tutorial was rewritten in April 2018.
We will create a chat example between two Android devices.
All the non-UI code is implemented in a class named BluetoothManager. It is initialized in Service_Create of the starter service.
It is always better to implement communication related code in a service or a class initialized from a service. This way the communication state is not affected by the activities more complicated state.
The activities call the class methods directly. Calling the activities subs is done with CallSub. Remember that CallSub doesn't do anything if the activity is paused.
The first activity, the main activity, shows two buttons. One for searching other devices and one for listening for connections.
Searching other devices requires a "dangerous" permissions (see the runtime permissions tutorial for more information).
Code:
Sub btnSearchForDevices_Click
rp.CheckAndRequest(rp.PERMISSION_ACCESS_COARSE_LOCATION)
Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
If Result = False Then
ToastMessageShow("No permission...", False)
Return
End If
Starter.Manager.SearchForDevices
End Sub
The second button sends an intent to the OS to make the device discoverable and then calls Serial.Listen.
Once a connection is established:
1. AsyncStreams is initialized in prefix mode (see the AsyncStreams tutorial for more information).
2. The ChatActivity is started.
Notes
- There is a potential issue on Android 8.0+ devices related to the change in the service life cycle explained here:
https://www.b4x.com/android/forum/threads/automatic-foreground-mode.90546/#content
If the app is in the background for several minutes then the starter service will be destroyed and the manager will be paused until the app is killed and restarted.
A possible workaround is to call ExitApplication from Service_Destroy of the starter service.
Note that this issue will not happen with B4A 8.1+ (not released at the time of writing) as the starter service implementation will be modified in such way that it will never be paused.
- In this example we send text messages. Use B4XSerializator to send more complex types.