Android Tutorial Android Bluetooth / BluetoothAdmin Tutorial

Discussion in 'Tutorials & Examples' started by Erel, Feb 7, 2012.

Thread Status:
Not open for further replies.
  1. Erel

    Erel Administrator Staff Member Licensed User

    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).

    Sub btnSearchForDevices_Click
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    If Result = False Then
    ToastMessageShow("No permission..."False)
    End If
    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.



    - In this example we send text messages. Use B4XSerializator to send more complex types.

    Attached Files:

    Last edited: Sep 22, 2018
  2. raphaelcno

    raphaelcno Active Member Licensed User

    Two different colours for received and sent text

    That looks very nice.
    Is it possible to show "txtLog" with two different colours, for instance received text in red colour and sent text in blue colour?
    Is it also possible to show a time stamp ("12:34:56.789" or similar) before the text "You" and "Me"?
  3. Erel

    Erel Administrator Staff Member Licensed User

    It is better to start a new thread for these questions. You can use the RichString library to change the colors. Adding the time stamp should be pretty simple. You should add it in Sub LogMessage.
  4. walterf25

    walterf25 Well-Known Member Licensed User


    Hi Erel, i tried your example for bluetooth communication, and i must say is very good, however i'm using a RN-42 bluetooth i bought from sparkfun electronics, i'm able to connect to it via my HTC Evo shift i wrote a small program in visual studio to receive and send the text strings, i can receive the strings ok sent from my phone to my program written in visual studio, but when i send a string back to the bluetooth module, your program shuts down giving me a foreclosed error, i have tried this before with app inventor and it should work ok, the module is connected to my computer through a serial port, i need help figuring out where this is going wrong! can you maybe give me some tips.

  5. Jonas

    Jonas Member Licensed User

    I guess you dont send the prefix characters from you VS program which is needed when using prefix mode. Try not using prefix mode and you will see everyting will work!

  6. walterf25

    walterf25 Well-Known Member Licensed User

    Hi Jonas, thanks for your reponse, i'm not sure what you mean when you say prefix mode, can you elaborate a little more?


  7. Jonas

    Jonas Member Licensed User

    When you initialize the Asyncstream in this exemple the following code is

    AStream.InitializePrefix(Main.serial1.InputStream, True, Main.serial1.OutputStream, "AStream")
    But if you instead use

    AStreams.Initialize(Main.Serial1.InputStream, Main.Serial1.OutputStream, "AStreams")
    The program wont be halted beacuse it cant find the prefix in the incoming data stream.

    When the AStreams_NewData event triggers it might just hold a few bytes of the whole message you want to receive so you have to append the Buffer data into a variable and manipulate the data later.
    Or just update txtLog.Text = txtLog.Text & the buffer data

    Last edited: Feb 22, 2012
    iotaprime and Opa like this.
  8. walterf25

    walterf25 Well-Known Member Licensed User

    bluetooth com

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

    Kevin L. Johnson likes this.
  9. raphaelcno

    raphaelcno Active Member Licensed User

  10. pinoy_ako

    pinoy_ako Member Licensed User

    i tried compiling the provided sample with b4a 1.6 and am having error.
    is this sample not compatible with 1.6? or im just missing something?

  11. pinoy_ako

    pinoy_ako Member Licensed User

    worked ok now. just updated the serial lib.:sign0104:
  12. pinoy_ako

    pinoy_ako Member Licensed User

    To those who want to make use of .Initializeprefix with a uart bluetooth or pc bluetooth spp, the prefix value format is:
    "b b b B x"
    b = 0
    B = string lenght
    x = string
  13. nicodh

    nicodh Member Licensed User


    I'm new to b4a and I like it so far. But, always a but, I'm having trouble to use this example with my bluetooth module.
    I'm trying to comunicate to multiwii (flight controller).
    If I send for example a letter M I should receive from him a byte array (I will then serialize it as needed).

    I have to say this works perfectly with any serial com like telnet, hercules putty... even the bluetooth chat example from android sdk.

    I tried the old and this example but no results.

    I have several possibilities, like for example sending a "#" will open a command line interpreter and normally I can change some parameters. But with this or the old example it doesn't work.

    What could I test?
  14. Erel

    Erel Administrator Staff Member Licensed User

    Make sure not to use prefix mode in this case.

    Do you get any error?
  15. nicodh

    nicodh Member Licensed User

    Hi erel, I tried with no prefix using
    AStream.Initialize(Main.Serial1.InputStream, Main.Serial1.OutputStream, "AStream")
    But it does the same, no response.

    When using prefix, I have a timeout and the app freezes. When not using prefix I have no response (or the system shows me the same data I entered)
    I will try to do some screenshots.

    I'm thinking I have to use the unsecure connection (I remember doing that with bluetooth chat). But I can't figure out what to put in the port value:

    ConnectInsecure (Admin As BluetoothAdmin, MacAddress As String, Port As Int)

    EDIT: Ok it works with insecure using port 1.
    Last edited: Apr 5, 2012
  16. Erel

    Erel Administrator Staff Member Licensed User

    Prefix mode can only be used if both sides adhere to this specific protocol. This is not the case here.

    If the Android SDK bluetooth chat works properly then you don't need to use ConnectInsecure.
  17. nicodh

    nicodh Member Licensed User

    Bluetooth chat works with a small workaround, I remember changing some line on the connection settings, other wise it didn't connect.
  18. nicodh

    nicodh Member Licensed User

    Hi again, I managed to receive the data from my stm32 via bluetooth, using the astream with prefix and secure connection.

    Now my problem is that I know the size of the stream I should receive, in my case 155 bytes.
    Sometimes I receive all, sometimes I don't, I made an if statement that compare this length, and if not the good one, it re send a command to the device so it resend the data.
    This works randomly and sometimes it takes a lot of time.

    How can I do to make the astream to wait for the 155 bytes?
  19. Erel

    Erel Administrator Staff Member Licensed User

    Are you sure that you are using AsyncStreams in prefix mode?
  20. pinoy_ako

    pinoy_ako Member Licensed User

    wow. you have a multiwii. ayos!

    i just received my mwc quadcopter last friday. and the final end i have in my mind is to control it with android.

    i haven't tried sending a 155byte string. i only tried 16bytes max from a uart bt module in prefix mode, and i did not encounter any problem. i'll try to send 155 or 255 byte later when i get home. 'will post result after.
Thread Status:
Not open for further replies.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice