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: 7,104
Last edited:

raphael75

Active Member
Licensed User
Longtime User
Two different colours for received and sent text

That looks very nice.
Is it possible to show "txtLog" with two different colours, for instance received text in red colour and sent text in blue colour?
Is it also possible to show a time stamp ("12:34:56.789" or similar) before the text "You" and "Me"?
 

walterf25

Expert
Licensed User
Longtime User
Bluetooth

Hi Erel, i tried your example for bluetooth communication, and i must say is very good, however i'm using a RN-42 bluetooth i bought from sparkfun electronics, i'm able to connect to it via my HTC Evo shift i wrote a small program in visual studio to receive and send the text strings, i can receive the strings ok sent from my phone to my program written in visual studio, but when i send a string back to the bluetooth module, your program shuts down giving me a foreclosed error, i have tried this before with app inventor and it should work ok, the module is connected to my computer through a serial port, i need help figuring out where this is going wrong! can you maybe give me some tips.

Thanks,
Walter
 

Jonas

Member
Licensed User
Longtime User
I guess you dont send the prefix characters from you VS program which is needed when using prefix mode. Try not using prefix mode and you will see everyting will work!

/J
 

walterf25

Expert
Licensed User
Longtime User
I guess you dont send the prefix characters from you VS program which is needed when using prefix mode. Try not using prefix mode and you will see everyting will work!

/J

Hi Jonas, thanks for your reponse, i'm not sure what you mean when you say prefix mode, can you elaborate a little more?

:signOops:

thanks,
Walter
 

Jonas

Member
Licensed User
Longtime User
When you initialize the Asyncstream in this exemple the following code is

B4X:
AStream.InitializePrefix(Main.serial1.InputStream, True, Main.serial1.OutputStream, "AStream")

But if you instead use

B4X:
AStreams.Initialize(Main.Serial1.InputStream, Main.Serial1.OutputStream, "AStreams")

The program wont be halted beacuse it cant find the prefix in the incoming data stream.

When the AStreams_NewData event triggers it might just hold a few bytes of the whole message you want to receive so you have to append the Buffer data into a variable and manipulate the data later.
Or just update txtLog.Text = txtLog.Text & the buffer data

/J
 
Last edited:

walterf25

Expert
Licensed User
Longtime User
bluetooth com

I guess you dont send the prefix characters from you VS program which is needed when using prefix mode. Try not using prefix mode and you will see everyting will work!

/J

thanks Jonas that worked like a charm, thanks much buddy!

cheers,
Walter
 

raphael75

Active Member
Licensed User
Longtime User

pinoy_ako

Member
Licensed User
Longtime User
i tried compiling the provided sample with b4a 1.6 and am having error.
is this sample not compatible with 1.6? or im just missing something?

thanks
 

pinoy_ako

Member
Licensed User
Longtime User
To those who want to make use of .Initializeprefix with a uart bluetooth or pc bluetooth spp, the prefix value format is:
"b b b B x"
Where:
b = 0
B = string lenght
x = string
 

nicodh

Member
Licensed User
Longtime User
Hello!

I'm new to b4a and I like it so far. But, always a but, I'm having trouble to use this example with my bluetooth module.
I'm trying to comunicate to multiwii (flight controller).
If I send for example a letter M I should receive from him a byte array (I will then serialize it as needed).

I have to say this works perfectly with any serial com like telnet, hercules putty... even the bluetooth chat example from android sdk.

I tried the old and this example but no results.

I have several possibilities, like for example sending a "#" will open a command line interpreter and normally I can change some parameters. But with this or the old example it doesn't work.

What could I test?
Thanks!
 

nicodh

Member
Licensed User
Longtime User
Hi erel, I tried with no prefix using
AStream.Initialize(Main.Serial1.InputStream, Main.Serial1.OutputStream, "AStream")
But it does the same, no response.

When using prefix, I have a java.io timeout and the app freezes. When not using prefix I have no response (or the system shows me the same data I entered)
I will try to do some screenshots.

I'm thinking I have to use the unsecure connection (I remember doing that with bluetooth chat). But I can't figure out what to put in the port value:

ConnectInsecure (Admin As BluetoothAdmin, MacAddress As String, Port As Int)


EDIT: Ok it works with insecure using port 1.
 
Last edited:

nicodh

Member
Licensed User
Longtime User
Prefix mode can only be used if both sides adhere to this specific protocol. This is not the case here.

If the Android SDK bluetooth chat works properly then you don't need to use ConnectInsecure.

Bluetooth chat works with a small workaround, I remember changing some line on the connection settings, other wise it didn't connect.
 

nicodh

Member
Licensed User
Longtime User
Hi again, I managed to receive the data from my stm32 via bluetooth, using the astream with prefix and secure connection.

Now my problem is that I know the size of the stream I should receive, in my case 155 bytes.
Sometimes I receive all, sometimes I don't, I made an if statement that compare this length, and if not the good one, it re send a command to the device so it resend the data.
This works randomly and sometimes it takes a lot of time.

How can I do to make the astream to wait for the 155 bytes?
 

pinoy_ako

Member
Licensed User
Longtime User
@nicodh.
wow. you have a multiwii. ayos!

i just received my mwc quadcopter last friday. and the final end i have in my mind is to control it with android.

i haven't tried sending a 155byte string. i only tried 16bytes max from a uart bt module in prefix mode, and i did not encounter any problem. i'll try to send 155 or 255 byte later when i get home. 'will post result after.
 
Status
Not open for further replies.
Top