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

paolofi

Member
Licensed User
Longtime User
Hi, I have a question for you,
I'll try to connect my Arduino too, with the SerialExample example I able to receive some date before to lost the connection, I believe that would be a timing problem.
With this Bluetooth example source I can not even connect.
From the micro side I connect and start to send data, requires to send some protocol data before?
What kind of micro and B4A software used?

best regards.

I see, thanks a lot for that info Erel, now i understand a little better the whole bluetooth communication deal, i was actually able to program a microcontroller and read an analog voltage and display the voltage on my android phone last night, I will try to post some pictures when i get a chance, B4Android rocks.

cheers,
Walter
 

nicholas99

Member
Licensed User
Longtime User
Mindset EEG problem

Hi Erel, I'm trying to receive data packets from a NeuroSky EEG headset using your example program. I'm not using prefix mode. The only way I can receive data from the device is using ConnectInsecure and then I only receive 9 bytes immediately after the device connects even though packets are transmitted in about one-second intervals.
I assumed that AStream_NewData was triggered continuously, but b4a Bluetooth programming is new to me so I could easily be mistaken.
Can you advise?
 

nicholas99

Member
Licensed User
Longtime User
Thanks for the quick reply. I have read through every tutorial and relevant post about Bluetooth but can't find any hint as to why I only receive a few bytes from the device. It is detected, paired and connected and I know that it is producing data packets (I have a PC app the shows the data being generated). I've tried just about every combination of Connect and Initialize. Can you suggest anything else for me to try or what the problem could be?
 
Last edited:

reddtechnologies

Member
Licensed User
Longtime User
Asyncstreams [Bluetooth Serial Communications] missing first byte

I am continously sending =123456# from my microcontroller to my Android device via Bluetooth but I am always receiving = ahead of the rest of the string (123456#). I have read Asyncstreams documentation but still can't understand why this is happening. Its a single string that I am sending out (not one character at a time) so I expecting everything to arrive at the same time. Any suggestions or recommended reading will be much appreciated.
 

reddtechnologies

Member
Licensed User
Longtime User
Can you post the reading code?

AsyncStreams will never add a '=' character.

Erel, my apologies for not mentioning this before but I was playing around with Bluetooth example with the only difference that I have changed the code to initialize AStream in normal mode (not prefix mode). Here is the code:

Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("2")
If AStream.IsInitialized = False Then
AStream.Initialize(Main.serial1.InputStream,Main.serial1.OutputStream, "AStream")
End If
txtLog.Width = 100%x
End Sub


Sub AStream_NewData (Buffer() As Byte)
LogMessage("You", BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
End Sub

Re: '=' character, are you saying that AsyncStreams ignores '=' when it receives it OR is it that it receives and recognizes it but never reports it? If this is correct then what can we do to handle serial data that starts with '=' sign or '=' sign is somewhere in the middle (e.g. "ADC=0xFFFF")?
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
Please use [ code ] [ /code ] tags (without spaces) when posting code.

I previously misread your post. I thought that you are getting a '=' character from nowhere.

When you are not using Prefix mode then the data is sent as is. There is no guarantee that it will arrive at once. It depends on the native network driver.
Prefix mode takes care of it by sending the message length.

In your case the solution should be to append the string to a StringBuilder and then check for = and #. If you found those then you found a complete message. In that case you should remove it from the StringBuilder and continue looking for messages.
 

pjoconn

Member
Licensed User
Longtime User
Getting a java.io.ioexception

:sign0085:Hello, I'm very very new to Android programming so please forgive my novice question. I have a Nexus 7 and a licensed version of B4A. Two day's ago I compiled an ran the Bluetooth example and it worked fine. Today it finds the BT on my PC but when I try to connect I get the following error:
java.io.Ioexception: read error socket might closed read ret -1
I tried rebooting the nexus but I get the same result. Thanks in advance to all that reply.
 

pjoconn

Member
Licensed User
Longtime User
java io error

Erel,
Thanks, re-pairing (forgive the pun) worked. I'm using RealTerm on my PC. Again, thanks for the fast and accurate responce.

Pat
 

kwalter

Member
Licensed User
Longtime User
java.lang.OutOfMemoryError

Hi Erel,

I have a problem with the Bluetooth Asyncstream.
If I want to send or receive something via Bluetooth, the Android program crashes with an error message:

connected: true
** Activity (main) Pause, UserClosed = false **
** Activity (chatactivity) Create, isFirst = true **
** Activity (chatactivity) Resume **
java.lang.OutOfMemoryError
at anywheresoftware.b4a.randomaccessfile.AsyncStreams$AIN.run(AsyncStreams.java:172)
at java.lang.Thread.run(Thread.java:856)
** Activity (chatactivity) Pause, UserClosed = true **
** Activity (main) Resume **

what is wrong?

best regards
kwalter
 

kwalter

Member
Licensed User
Longtime User
AsyncStream Problems

Hi Erel,
Ok, thank you've found the problem.
I'm new to B4A, how can I sort the output of the stream?
I send control commands to a Bluetooth device:

: F1 & Chr (13)
: F2 & Chr (13)
: a1 & Chr (13)
: D1 & Chr (13)
: a2 & Chr (13)
: D2 & Chr (13)

Each control character returns a response, which unfortunately currently not coming to the series but confused?

Greetings
kwalter
 

terwelu

New Member
Licensed User
Longtime User
Connection refused problem

Hi Erel,

I'm new with Android Programming.
I'm now trying to connect my Arduino with my Android.

The connection progress was successful until the step where Android was asking for the pairing code. After I put 0000, I got this message :

"Error connecting java.io.IOException: Connection refused"

Can you give me a clue what is the problem with my connection ?

Thanks in advance !

Regards,
Ricki
 
Status
Not open for further replies.
Top