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

jcohedman

Member
Licensed User
Longtime User
in the sample program "Bluetooth" I am using AStreams.Initialize(Main.serial1.InputStream, Main.serial1.OutputStream, "AStreams"), I have an arduino board sending a string that I can manage, it comes as: "0161234567891011123".
It function for 2 or 3 hours, and then it blocks receiving data...
Can anybody tell me what I do wrong?
Thanks in advance. Happy New Year to all!
 

jcohedman

Member
Licensed User
Longtime User
Do you get any error? What are you doing with the string?
any error.
the string is showed as the sub:
Sub AStreams_NewData (Buffer() As Byte)
LogMessage("You", BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
End Sub

it only stop receiving data.
I read the serial port of arduino, with the PC, and the data continues...
 

jcohedman

Member
Licensed User
Longtime User
Yes. I wrote this code:
Sub AStream_Error
ToastMessageShow("Se interrumpió la conexión.", True)
Informe= "Error Astream"
CrearTablaBaseDatos ' (generates a .db file)
Activity.Finish
End Sub

Sub AStream_Terminated
Informe= "Astream Terminated"
CrearTablaBaseDatos
AStream_Error
End Sub​

and had no data of any type of error...

can't be a memory issue?
It seems like AStream is stopped.
 

garymq

New Member
Licensed User
Longtime User
Hello I have been using the Bluetooth program from the tutorial to connect between a HC07 BT module. This is a nice BT module which can connect easily to the PC serial port. I can send and receive data across the BT connection. (Using Teraterm for the PC terminal program.)

It all works quite well, thanks for the demo program.

However I have a question about shutting down the BT connection.

I want to shut down the BT connection from within the program, and allow the user to restart the Discovery process.
So I call admin.Disable. The connection stops (status goes to OFF), but when I try to restart the discovery process (admin.StartDiscovery), it always returns False. Of course, if I stop and start the program again, everything is OK - the Discovery process starts without problems.

In general, what should I do to correctly shut down the BT connection from inside the program (in addition to admin.Disable), so that a new discovery process can start again?

Thanks
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
@jcohedman, if it was a memory issue then the whole app would have crashed with an out of memory exception. Android Bluetooth is far from being perfect. Its stability varies between different devices. You should make sure that the Terminated event and Error event are not raised. Add a Log message.

You should also check the unfiltered logs. Maybe there is an error there.

How are you keeping the phone running for several hours?

In general, what should I do to correctly shut down the BT connection from inside the program (in addition to admin.Disable), so that a new discovery process can start again?
Are you enabling it before starting the discovery process?
 

garymq

New Member
Licensed User
Longtime User
Are you enabling it before starting the discovery process?

Yes, I am re-enabling the BTadmin before re-starting the discovery process.
The sequence is as follows:
1. Running the tutorial Bluetooth.b4a program - Everything working fine.
2. Added button control to call admin.disable - admin.status goes to OFF
3. Attempt to restart the discovery process: admin.enable, then admin.StartDiscovery. (use btnSearchForDevices_Click)
4. But now admin.StartDiscovery always returns False (program reports "Error starting discovery process")

As far as I can tell I am doing everything that the program does when it starts up (when Discovery works fine), but when I try to re-start Discovery a second time, StartDiscovery always returns False.
 

garymq

New Member
Licensed User
Longtime User
The Bluetooth adapter is not immediately ready. You should handle the StateChanged event.

See B4A-Bridge source code. When you press on the Allow discovery it will enable the adapter and then start the process.

Working now!

Yes, needed to wait for BT to become enabled. I also needed to understand a bit better the use of Admin_StatusChange to check status, and a few other things about initialization.

Thanks for the assistance. Especially appreciate the speedy responses.

(Working thru this problem has let me learn B4A and environment. Quite good!)
 

jcohedman

Member
Licensed User
Longtime User
@jcohedman, if it was a memory issue then the whole app would have crashed with an out of memory exception. Android Bluetooth is far from being perfect. Its stability varies between different devices. You should make sure that the Terminated event and Error event are not raised. Add a Log message.

You should also check the unfiltered logs. Maybe there is an error there.

How are you keeping the phone running for several hours?


Are you enabling it before starting the discovery process?


I'm using an Acer Iconia model B1-A71, with Android 4.1.2, 7" tablet, connected to it's charger, and runs all day without problems...

I'll try with WiFi Direct and tell you.
Thanks!
 

ppgirl

Member
Licensed User
Longtime User
I'm using an Acer Iconia model B1-A71, with Android 4.1.2, 7" tablet, connected to it's charger, and runs all day without problems...

I'll try with WiFi Direct and tell you.
Thanks!


I have same problem between mobile LENOVO A789 (Android 4.0.4 , MTK 6577), Sub AStreams_NewData will not rasie after send some minute data , very randomly.

And the bluetooth will don't re-connect at all . it prompt "SDP" or other error.

And can not switch on after switch off bluetooth using system action bar .

otherwise , It become ok after power-down / power-on mobile.
 

ppgirl

Member
Licensed User
Longtime User
Are you handling AStreams_Error and AStreams_Terminated events?

If yes then it might be a hardware / os problem. On some devices the Bluetooth adapter is not really reliable.


I checked it don't rasie AStreams_Error or AStreams_Terminated events , it looks like buffer overflow problem.

Thank Erel as soon as ...
 

GMan

Well-Known Member
Licensed User
Longtime User
SOME BlueTooth devices has not the full "capacity" of protocols - some are only for Voice, some only Data, some VPN, some PAN, some mixed and others different etc.
Can you establish ANY connection with your device, maybe from/to PC with a BT-USB-Stick, from/to another Android device or so ?
 

MercAMG

Banned
This tutorial is an improved version of the previous Serial tutorial.
We will create a chat example between two Android devices.

Using BluetoothAdmin we search for in-range devices and then allow the user to connect to a device. If the device were not paired before then a dialog will show to confirm the pairing process.

The first activity includes two buttons:

SS-2012-02-07_17.31.22.png


"Search for devices" button will start a discovery process that takes about 12 seconds.

"Make device discoverable" button does two things. First it sends an Intent that makes the device discoverable for 300 seconds. It then calls Serial1.Listen to listen for incoming connections.

If the connection is established successfully then we start the second activity:

SS-2012-02-07_17.25.41.png


In the second activity we use AsyncStreams to send and receive messages.
As we use AsyncStreams in both sides of the connection we can easily use "prefix mode". In this mode we always receive complete messages.

The code is attached.

Example of transferring files over Bluetooth or Wifi: http://www.b4x.com/forum/basic4andr...nd-receive-files-asyncstreams.html#post177049
 

a2stepper

Member
Licensed User
Longtime User
this worked on version 3.0 of b4a but i got the new 3.2 ba and this bluetooth example is now working. any ideas?
paul
 
Status
Not open for further replies.
Top