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

Andy Wu

Member
Licensed User
Longtime User
use blilt-in is ok,but using Bluetooth.zip to connect bluetooth will error.

and error message is "LastException.Message = java.io.IOException: read failed, socket might closed or timeout, read ret: -1"

I dont know how to slove this problem...
 

GMan

Well-Known Member
Licensed User
Longtime User
Do you use AsyncMode with or without PrefixMode ?
Try to change that
 

irda

Member
Licensed User
Longtime User
You cannot set the pin automatically. Note that once the device are paired they do not need to be paired again.

You can try to connect with ConnectInsecure. However you will need to find the correct port (usually between 1 to 10).

But, isn't there any way to set the pin without human intervention (paired programamatically)?
 

Beja

Expert
Licensed User
Longtime User
Connection is broken.
This is the message that pops up each time I try to receive response from other device.
Pairing is ok.
sending is ok.
the log is:

LogCat connected to: emulator-5554
** Activity (main) Create, isFirst = true **


** Activity (main) Resume **


java.lang.NullPointerException


at anywheresoftware.b4a.objects.Serial$BluetoothAdmin.IsEnabled(Serial.java:394)
at anywheresoftware.b4a.samples.bluetooth.main._activity_resume(main.java:324)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:174)
at anywheresoftware.b4a.BA.raiseEvent(BA.java:158)
at anywheresoftware.b4a.samples.bluetooth.main.afterFirstLayout(main.java:104)
at anywheresoftware.b4a.samples.bluetooth.main.access$100(main.java:16)
at anywheresoftware.b4a.samples.bluetooth.main$WaitForLayout.run(main.java:76)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
java.lang.NullPointerException

p.s.
I used HC-6 BT module connected to PC.
Tried to remove the Prefix but no efeect.
Any help appreciated.
 

Beja

Expert
Licensed User
Longtime User
Thanks Erel,
I unzipped and run it without modification.. everything is fine except when trying to send some data back to the device.

main activity:
B4X:
    If FirstTime Then
        admin.Initialize("admin")
        serial1.Initialize("serial1")

ChatActivity:
B4X:
Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("2")
    If AStream.IsInitialized = False Then
        AStream.InitializePrefix(Main.serial1.InputStream, True, Main.serial1.OutputStream, "AStream")
    End If
 

BETORRR

New Member
Licensed User
Longtime User
Please help me!

I NEED to use bluetooth because my work. I'm trying example bluetooth but ALWAYS recive this messge: Service Discovery Fail
I make Erel say -uncomment - Serial1 but don't work.
Help!
 

enrique1

Member
Licensed User
Longtime User
Hi All,

is it possible to get the battery level from a bluetooth connected device? I mean, the other device hasn't got installed an app and it cannot send this information, only allow to the other device connect to him.

Thanks in advice, I think this question has not posted before.
 

Kevin L. Johnson

Member
Licensed User
Longtime User
bluetooth com



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

cheers,
Walter

Walter, Jonas, Thanks to both of you for raising and solving the issue!
I had the same issue with a Sparkfun Bluetooth RNBT-25D3 and...
B4X:
'Switching 
   'AStream.InitializePrefix(Main.serial1.InputStream, True, Main.serial1.OutputStream, "AStream")
'to...
   AStream.Initialize(Main.serial1.InputStream, Main.serial1.OutputStream, "AStream")
also worked like a charm.
Thanks to Erel and Anywhere software for a great product and a great community too!
Kevin
 

Dogbonesix

Active Member
Licensed User
Longtime User
Problem Connecting with the BlueTooth tutorial - first try.
I was able to Pair my Cell Phone and Acer Tablet. Search for devices finds my tablet. But when I select "Choose device to connect" all I get is connection: false. So, I downloaded a BlueTooth Chat program from the play store to see if it will work - it does. What can go wrong with (line 85) serial1.Connect(connectedDevice.Mac)? The log shows - java.io.IOException:read failed, socked might be closed or timeout, read ret: -1 but that does not help me much. And insight will be greatly appreciated.
 
Status
Not open for further replies.
Top