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

a2stepper

Member
Licensed User
Longtime User
Program paused of line :36
If admin.IsEnabled = False Then

this is using the improved chat using bluetooth example.
is did work using the 3.0 version.
thanks.
paul


OK :) just figured it out, no bluetooth adapter. thanks...
paul
 

jcohedman

Member
Licensed User
Longtime User
in my case Astreams_Newdata stops receiving data (in this moment, receives a "1" and no more data come, the app 'still sends the string question via bluetooth...
B4X:
Sub Timer1_Tick

If AStreams.IsInitialized = True Then
        estringb.Initialize       
        TextWriter.Write("r")     'CON ESTO ESCRIBO UNA LETRA r, PARA INTERROGAR AL BLUETOOTH, LUEGO RESPONDE (YOU WISH...)
        TextWriter.Flush
End If

End Sub



B4X:
Sub AStreams_NewData (Buffer() As Byte)   
    string= BytesToString(Buffer, 0,  Buffer.Length, "UTF-8")
    If (string.Length=8) Then
    Actualizar_datos
    End If
End Sub

Can anybody help me? sorry for my english, I'm spanish native... ;)
 

PierPaduan

Active Member
Licensed User
Longtime User
Woowwww....
Thanks a lot for this tutorial Erel, I has been able to modify it and communicate with our BT device in a couple of hours. Very very useful.
 

Ashley

Member
Licensed User
Longtime User
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
Hi Earl, I have two phones a Samsung S2 and S3, I have each of them paired individually to a PC using '32 feet' for the connection. Using a hacked version of this chat connection, the S2 phone connects as either a client or a server and works perfectly, but the S3 only connects as a client and not a server. When trying to connect as server I get a Error 'Java IO exception, Unable to Start Service Discovery' on the phone, any Ideas what the difference between the phones would be?. Any help would be appreciated.
Ashley
 
Last edited:

Ashley

Member
Licensed User
Longtime User
Are you connecting the two devices to each other?
No, it is only a one way connection to the PC via '32 Feet' on win 8.1, I don't need any return data to the phone. Although I have previously connected the phones to each other using your original chat software and they connected and worked ok. My current project is using the phone's position sensors to rotate a object in 3D live via blue tooth, with the phone as a server transmitting the data on a timer event. My old phone (S2) connects and transmits perfectly but the new one (S3) just will not connect with the exact same B4A code. It is paired and finds the PC Ok, but when I press the connect button on the phone, it fails with error as previously stated. I don't know what or how or why. Any ideas?. FYI great IDE.
PS!!!!!!!!Sorry but the PC is the server and the phone the client, my bad!!!!.
 
Last edited:

GMan

Well-Known Member
Licensed User
Longtime User
Do you use the Async PreFixMode ?
 

Ashley

Member
Licensed User
Longtime User
I am using prefixMode, but this is not the problem, my old S2 phone connects and is working perfectly. The new S3 connects to the old S2 with this chat software but will not connect to the PC, where as the S2 does. I was using non prefix mode earlier on but found the data stream awkard. This mode had no influence on the connection, the error still appeared. Is there another connectionsetting or something other than the UUID that maybe needed?. The B4A code I am installing on the Samsung phones is identical.
 

DavideV

Active Member
Licensed User
Longtime User
I am using prefixMode, but this is not the problem, my old S2 phone connects and is working perfectly. The new S3 connects to the old S2 with this chat software but will not connect to the PC, where as the S2 does. I was using non prefix mode earlier on but found the data stream awkard. This mode had no influence on the connection, the error still appeared. Is there another connectionsetting or something other than the UUID that maybe needed?. The B4A code I am installing on the Samsung phones is identical.

Have you tried a simple file transfer over bluetooth from the S3 to your pc?
Try send an image, for example, from the gallery to your pc to see if the connection work.
If you get problem try update the BT manager software on pc side.
I had a similar problem with my S4 mini on a Dell laptop win xp. Never had problem with the same phone on win7.

You can try to unpair and then pair again the phone with the pc but i think you have already done....

Bye.
DavideV
 

Ashley

Member
Licensed User
Longtime User
Have you tried a simple file transfer over bluetooth from the S3 to your pc?
Try send an image, for example, from the gallery to your pc to see if the connection work.
If you get problem try update the BT manager software on pc side.
I had a similar problem with my S4 mini on a Dell laptop win xp. Never had problem with the same phone on win7.

You can try to unpair and then pair again the phone with the pc but i think you have already done....

Bye.
DavideV
Hi DavideV
Sending files from phone to PC via B/T with default phone software worked fine. You would not believe it, but after doing that, the phone now connects with no problems to PC via '32 feet'. Un F'n believable. Thanks DavideV. Yahoo! PS the phone was correctly paired prior to this.
 

DavideV

Active Member
Licensed User
Longtime User
Hi Ashley, nice to know :)
I believe you... it's a strange behaviour of the pc software... i use BT modules from years and i saw a lot of strange things... :(

Bye
 

GMan

Well-Known Member
Licensed User
Longtime User
Hi DavideV
Sending files from phone to PC via B/T with default phone software worked fine. You would not believe it, but after doing that, the phone now connects with no problems to PC via '32 feet'. Un F'n believable. Thanks DavideV. Yahoo! PS the phone was correctly paired prior to this.
Mustn't a new device not be paired first with i.e. BlueSoleil or similar to/with the PC ?
After you done it, it works - before it can't.
 

Ashley

Member
Licensed User
Longtime User
Mustn't a new device not be paired first with i.e. BlueSoleil or similar to/with the PC ?
After you done it, it works - before it can't.
Hi GMan, not sure what your saying, but the new phone, was paired correctly thru the PC B/T connection manager, but it had never been used for a B/T connection. Once it was used to transfer a picture file using the default win software, I was then able to successfully connect it thru the '32 feet' software. It seems like this was needed to register the phone on the PC where as the '32 feet' would not, some registering code is missing?. It now connects perfectly.
Thanks, all the help the was appreciated,
Ashley
 
Last edited:

Andy Wu

Member
Licensed User
Longtime User
plz help me

I used the Bluetooth.zip of program. but it failed.

code line :

success = false

LastException.Message = java.io.IOException: read failed, socket might closed or timeout, read ret: -1

What could me solve it?


B4X:
Sub Serial1_Connected (Success As Boolean)

ProgressDialogHide

Log("connected: " & Success)

If Success = False Then

Log(LastException.Message)

ToastMessageShow("Error connecting: " & LastException.Message, True)

Else

StartActivity(ChatActivity)

End If

End Sub
 

GMan

Well-Known Member
Licensed User
Longtime User
What OS version are you using ?
success = false
LastException.Message = java.io.IOException: read failed, socket might closed or timeout, read ret: -1
Its a clear notice: read failed, because the socket didnt exist, wasnt opened or reaches the timeout.

When trying to connect: can you see your BT-devices or when does it crash ?
 

Andy Wu

Member
Licensed User
Longtime User
What OS version are you using ?

Its a clear notice: read failed, because the socket didnt exist, wasnt opened or reaches the timeout.

When trying to connect: can you see your BT-devices or when does it crash ?

No crash.

Built-In bluetooth pairing ok between devices(android to pc or android to android)

send or receive file OK by bluetooth ,also.


model : asus padfone X

android version : 4.4.2
 

GMan

Well-Known Member
Licensed User
Longtime User
plz help me

I used the Bluetooth.zip of program. but it failed.

code line :

success = false

LastException.Message = java.io.IOException: read failed, socket might closed or timeout, read ret: -1

What could me solve it?

???
So what exactly is the problem ?
 
Status
Not open for further replies.
Top