Android Tutorial Android Bluetooth / BluetoothAdmin Tutorial

Status
Not open for further replies.
Better implementation based on B4XPages:
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).
Note that you need to add the permission in the manifest editor:
B4X:
AddPermission(android.permission.ACCESS_FINE_LOCATION)

B4X:
Sub btnSearchForDevices_Click
   rp.CheckAndRequest(rp.PERMISSION_ACCESS_FINE_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.

SS-2018-04-04_12.02.01.jpg


Notes

- In this example we send text messages. Use B4XSerializator to send more complex types.
 

Attachments

  • Bluetooth.zip
    12.4 KB · Views: 6,660
Last edited:

red30

Well-Known Member
Licensed User
Longtime User
I managed to get the data but when i send data from the terminal, nothing comes. But if i send data from micricontroller via bluetooth, the data comes with this error. Moreover, [00 46 00 0b ff ff 00 00] must come but only [46 00 0b ff ff 00 00] comes. Where is the first bite?
 

Attachments

  • Screenshot_2016-09-20-13-14-59.png
    Screenshot_2016-09-20-13-14-59.png
    93.8 KB · Views: 574

padvou

Active Member
Licensed User
Longtime User
Thank you for this interesting post.
I try to use this code instead of having the user choose a device everytime. The devices are already paired in the OS settings menu.
But The serial1.connected returns false. Any ideas please?
B4X:
Sub StartConnection
   
    Dim PairedDevices As Map
    Dim L As List
    Dim Res As Int

    ToastMessageShow("Connecting.....",True)

    PairedDevices.Initialize
   
    Try
        PairedDevices = serial1.GetPairedDevices
    Catch
   
        serial1.Disconnect
    End Try

    If PairedDevices.Size = 0 Then
        Msgbox("Error connecting to device. Device not found","")
       
        Return
    End If

    If PairedDevices.Size = 1 Then
        Try
           
            Log(PairedDevices.Get(PairedDevices.GetKeyAt(0)))
            serial1.Connect(PairedDevices.Get(PairedDevices.GetKeyAt(0)))
            'serial1.ConnectInsecure(admin,PairedDevices.Get(PairedDevices.GetKeyAt(0)),1)
        Catch
       
            Msgbox("Connecting","Device error")
           
            serial1.Disconnect
           
        End Try
    Else
        L.Initialize

        For i = 0 To PairedDevices.Size - 1
            L.Add(PairedDevices.GetKeyAt(i))
        Next

        Res = InputList(L, "Choose device", -1)

        If Res <> DialogResponse.CANCEL Then
            serial1.Connect(PairedDevices.Get(L.Get(Res)))
            Log(PairedDevices.Get(L.Get(Res)))
        End If
    End If   
   
End Sub
 

red30

Well-Known Member
Licensed User
Longtime User
The search of bluetooth devices is a very long (about 1-2 minutes) on some devices, and when it is over, I choose the device and it gives me an error - as in the picture below. Why is this happening? How to fix it?
 

Attachments

  • 01.png
    01.png
    21.3 KB · Views: 466
  • 02.jpg
    02.jpg
    23.7 KB · Views: 433

red30

Well-Known Member
Licensed User
Longtime User
Not exactly, I took a programm from the first post as an example but used the tablet connected with bluetooth module HC-05(which is connected to microcontroller) instead of two android devices.
 

red30

Well-Known Member
Licensed User
Longtime User
dear friends,
I got the example from the first post.
When I write
B4X:
serial1.Connect(connectedDevice.Mac)
- it always works truly( with all devises).
When I write
B4X:
serial1.ConnectInsecure(admin,connectedDevice.Mac,1)
- it works only with some devices. Note - usually when the search is long (~1 min) the result is fail and it errors 01.png. Why is it so?

What is the difference between these three lines?
B4X:
serial1.ConnectInsecure(admin,connectedDevice.Mac,1)
serial1.Connect3(connectedDevice.Mac,1)
serial1.Connect(connectedDevice.Mac)

What is the difference between these two lines
B4X:
AStreams.Initialize(Main.Serial1.InputStream, Main.Serial1.OutputStream, "AStreams")
AStream.InitializePrefix(Main.serial1.InputStream, True, Main.serial1.OutputStream, "AStream")

Sorry for stupid questions :(
 

red30

Well-Known Member
Licensed User
Longtime User
At various devices search time "Device Bluetooth" different - why?
Can I change it?
 

red30

Well-Known Member
Licensed User
Longtime User
I meant: Why does search last not equally on different android devices? What determines this time?
 

red30

Well-Known Member
Licensed User
Longtime User
I run a default search for Bluetooth devices on the android-device. It finds one unit - "zebra" (this is my devise). Screenshot_2017-03-03-21-13-02[1].png When I run a search for devices in the program BluetoothAdmin Tutorial - it finds many (often more than 15) devices (but in fact this is only one device). Screenshot_2017-03-03-21-12-24[1].png Such a bug occurs only on devices with Spreadtrum CPU. Why? How to fix?
 

red30

Well-Known Member
Licensed User
Longtime User
It raises many times (4 or 8 or 9 or 15 or 23 etc.) Every time randomly. Screenshot_2017-03-05-17-14-26[1].png Screenshot_2017-03-05-17-13-36[1].png
Yes I use your programm from the first post. Screenshot_2017-03-05-17-12-40[1].png
Why so?
 
Last edited:

Computersmith64

Well-Known Member
Licensed User
Longtime User
It indeed looks like an OS bug. You can add the found devices to a Map with the MacAddress as the key to remove all duplicates.
I've noticed that issue too. The discovery will sometimes randomly list the same found device multiple times (although in my case I've only ever seen a device listed two or three times), then at other times will only list them once. Given that I've only ever seen a max of 3 instances of the same device I've never really worried about it, but I might try your suggestion.

I'm pretty sure I only ever see it after running the discovery more than once, so I wonder if the OS is caching the found devices list or something?

- Colin.
 
Status
Not open for further replies.
Top