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:

georgestheking

New Member
Licensed User
Longtime User
Hi,

I try to compile the bluetooth program using Basic4Android 1.9 but I get compilation errors !!!!!

Any update ?

Georges
 
Last edited:

maleche

Active Member
Licensed User
Longtime User
Help!
This is the error in Log I recived any time I try sending "ATZ" using the Bluetooth example. I changed to AsyncStreams per this post and still unable to send without lock ups.

java.lang.OutOfMemoryError at anywheresoftware.ba.randomaccessfile.AsyncStreams$AIN.run(AsyncStreams.java:168)
at java.lang.Thread.run(Thread.java:1019)
** Activity (chatactivity) Pause, UserClosed = true **


I just need to send via Bluetooth. any other examples to try?
Thanks!
DM
 

fdx12345

Active Member
Licensed User
Longtime User
Not running

When I run the example I keep getting a pause at line 26: If admin.IsEnabled=Flase. When I click continue, every thing is greyed out and nothing works.

I am running Basic4Android program as an administrator and my account (my pc) is type administrator.

Bill
 

balistreri1

Member
Licensed User
Longtime User
Hello Erel,

Bluetooth serial example bug report:
Sending 8 characters works fine.

Sending 9 or more characters results in extra
garbage data ahead of the actual data.

Key data is entered into a TextEdit called txtinput
and then sent out with the following button click

Sub btnSend_Click
AStream.Write(txtInput.Text.GetBytes("UTF8"))
txtInput.SelectAll
txtInput.RequestFocus
LogMessage("Me", txtInput.Text)
End Sub

Any help???
 

walterf25

Expert
Licensed User
Longtime User
Bluetooth help

Hi all, i finally got my RN-41 bluetooth Module to communicate with my Motorola Photon, i'm using the Erel's latest example, now i have another issue, while running this example i can send data and i see that i receive it on the other side, i'm basically just using a windows terminal to see what i send from the phone, now the problem is that when i want to reply from the terminal to the phone, i get an error that says.
"An error has occured in sub:
java.lang.Exception: Sub astreams_newdata was not found."

below is the log i get from the phone

FireFly-A09F:00:06:66:43:A0:9F
connected: true
java.lang.Exception: Sub astreams_newdata was not found.
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:142)
at anywheresoftware.b4a.BA$2.run(BA.java:244)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3806)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
java.lang.Exception: Sub astreams_newdata was not found.

any ideas why this is happening, just to clarify i got it working by using this
B4X:
serial1.ConnectInsecure(admin,connectedDevice.Mac,1)
and this
B4X:
AStream.Initialize(Main.Serial1.InputStream, Main.Serial1.OutputStream, "AStreams")
any help will be greatly appreciated guys.

Thanks,
:sign0085:
 

walterf25

Expert
Licensed User
Longtime User
Bluetooth help

I'm sorry everyone, for some reason the
B4X:
AStream.Initialize(Main.Serial1.InputStream, Main.Serial1.OutputStream, "AStreams")
'AStreams event was misspelled, i corrected to this
B4X:
Sub AStreams_NewData (Buffer() As Byte)
   LogMessage("You", BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
End Sub

now i have another question, when i send data back from the terminal to the phone, i don't receive all the characters in one line, i get one character per line, is there a way to receive the characters collect them in an array and then display them in the text box?

thanks,
Walter
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
This is exactly the purpose of "prefix" mode. Each message is prefixed with the message length and the library is responsible pass complete messages.

In regular mode the event is raised whenever there is data available. Your device probably sends the characters one after another. You will need to collect the data in your code.
 

walterf25

Expert
Licensed User
Longtime User
Bluetooth help

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
 

hpk2000

Member
serial.ConnectInsecure doubt

hi, how can I use the method? especially de Port argument. Don't know what to put there.
 

CSP

Member
Licensed User
Longtime User
Bluetooth program error

Will this example run on Android 1.6? The code runs perfect on my Droids, but on my Motorola Blur, I get this error on app execution:

Sorry! The application Bluetooth Example (process anywheresoftware.b4a.samples.bluetooth) has stopped unexpectedly. Please try again. (force close)

I've tried enabling bluetooth, disabling it, re-enabling it, resetting the phone, etc, all to no avail.
 

luke2012

Well-Known Member
Licensed User
Longtime User
Bluetooth file transfer

Hi!
It's possible to send a file between two paired devices ?
 

PD5DJ

Member
Licensed User
Longtime User
Hi Erel

I have some issues using the Asyncstreams,

Also caused by the fact im very new to this..

But neverteless I cant get my situation working..

I want to receive the following sentences from an embedded device.

Header = $
Stopper = #
Variable = 1234

$1234#

I have made a similar code for my embedded work, and that works fine..

This is what i made with Astreams_newdata.
I looks like I am missing a lot of characters sended in..

What I want is full control over all the characters 1 by 1 coming in, without missing some.

:sign0163:

B4X:
Sub AStreams_NewData (D() As Byte)
  
   Dd = BytesToString(D,0,1,"UTF-8")
   
   Dim Bytecounter As Byte
   Dim Cmaxchar As Byte :Cmaxchar = 20
   Dim Buffer As String
   Dim Dd As String
   
   If Connected Then
   
      If Bytecounter < Cmaxchar Then
   
         Bytecounter = Bytecounter + 1
      
         If Dd = "#" Then
            Buffer = ""
            Bytecounter = 0
            Label1.Text = Buffer
            
         
            Else If Dd = "$" Then
         
               Buffer= ""
               Bytecounter = 0
            Else
         
               Buffer = Buffer & Dd
                              
               If Bytecounter > 19 Then
                  Buffer = ""
                  Bytecounter = 0
               End If
            
         End If
      End If
   End If
   
End Sub
 
Status
Not open for further replies.
Top