Android Tutorial Android Serial tutorial

The code in this tutorial should not be used for new projects.
New tutorial:
https://www.b4x.com/android/forum/threads/android-bluetooth-bluetoothadmin-tutorial.14768/#content

This tutorial covers the Serial library. This library allows you to connect with other Bluetooth devices using virtual serial ports (RFCOMM).

The Serial library requires Android OS 2.0 or above (API level 5 or above).

We will build a simple chat example which allows two connected devices to send text messages.


serial_chat2.png


We created a process global object named Serial1 of type Serial.
Usually it is a good idea to initialize process objects in Sub Activity_Create when FirstTime is True. This way the objects will be initialized exactly once.

B4X:
Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        Serial1.Initialize("Serial1")
        Timer1.Initialize("Timer1", 200)
    End If
    Activity.LoadLayout("1")
    Activity.AddMenuItem("Connect", "mnuConnect")
    Activity.AddMenuItem("Disconnect", "mnuDisconnect")
End Sub
The next Sub running is Activity_Resume:
B4X:
Sub Activity_Resume
    If Serial1.IsEnabled = False Then
        Msgbox("Please enable Bluetooth.", "")
    Else
        Serial1.Listen 'listen for incoming connections
    End If
End Sub
Here we are checking if the Bluetooth device is enabled. If it is not enabled we ask the user to enable it. Note that by putting this code in Activity_Resume (and not Activity_Create) this test will happen every time the activity is resumed. So if the user goes to the settings screen, enables the device and then returns to our application we will now know that the Bluetooth is enabled.

If the Bluetooth is enabled we start listening for incoming connections. This allows other devices to connect with our device. This is not required if you connect to a device that listens for connections (like external GPS for example).
Note that calling Listen more than once doesn't do anything. So we are safe calling it this way.

When the user presses on the Connect menu item we show the user the list of known paired devices. When the user clicks on a device name we fetch its MAC address from the map and connect to it:

serial_chat_1.png


B4X:
Sub mnuConnect_Click
    Dim PairedDevices As Map
    PairedDevices = Serial1.GetPairedDevices
    Dim l As List
    l.Initialize
    For i = 0 To PairedDevices.Size - 1
        l.Add(PairedDevices.GetKeyAt(i)) 'add the friendly name to the list
    Next
    Dim res As Int
    res = InputList(l, "Choose device", -1) 'show list with paired devices
    If res <> DialogResponse.CANCEL Then
        Serial1.Connect(PairedDevices.Get(l.Get(res))) 'convert the name to mac address
    End If
End Sub
The connection is not established immediately. It will happen in the background. When the connection is established, the Connected event will be raised. A 'Success' parameter tells us if the connection is successful.
The Connected event can also be raised if an incoming connection is established.

B4X:
Sub Serial1_Connected (Success As Boolean)
    If Success Then
        ToastMessageShow("Connected successfully", False)
        TextReader1.Initialize(Serial1.InputStream)
        TextWriter1.Initialize(Serial1.OutputStream)
        timer1.Enabled = True
        connected = True
    Else
        connected = False
        Timer1.Enabled = False
        Msgbox(LastException.Message, "Error connecting.")
    End If
End Sub
If the connection was established successfully we can start the data transfer.
TextReader1 and TextWriter1 are process global object. We now initialize them using the serial stream. This will allow us to send and receive text over our newly created connection.
Timer1 is used to test whether there is incoming data (and read this data). Now we enable it and start listening.

If the connection is not successful we retrieve the exception and show it.

Sending messages - When the user presses on btnSend we send the text:
B4X:
Sub btnSend_Click
    If connected Then
        TextWriter1.WriteLine(txtSend.Text)
        TextWriter1.Flush
        txtSend.Text = ""
    End If
End Sub
'connected' is a variable that we use to know if we are currently connected.
Note that we call Flush after writing the text. This way we make sure that TextWriter doesn't buffer the text and sends it right away.

Receiving messages - Whenever the timer ticks we check if there is any data waiting to be read. If there is, we read it and add it to the large EditText:
B4X:
Sub Timer1_Tick
    If connected Then
        If TextReader1.Ready Then 'check if there is any data waiting to be read
            txtLog.Text = txtLog.Text & TextReader1.ReadLine & CRLF
            txtLog.SelectionStart = txtLog.Text.Length
        End If
    End If
End Sub
TextReader.ReadLine is a blocking call. It waits till there is at least a single character to be read. Therefore we need to test TextReader.Ready if we don't want to block our application.

This application can also be used to connect with non-Android devices.
An external GPS for example:
serial_3.png


The external GPS continuously sends its data as text.
I actually had quite an interesting conversation with the external GPS...

The program is attached.

Edit: It is recommended to use the new AsnycStreams object instead of polling the available bytes parameter with a timer. Using AsyncStreams is simpler and more reliable.
 

Attachments

  • SerialExample.zip
    6.3 KB · Views: 10,549
Last edited:

rvctx

New Member
Licensed User
Smartphones Bluetooth serial port

Hello,

is the B4A serial port library working with any smartphone running Android 2.2 or more ?

Best Regards,

Herve
 

AlpVir

Well-Known Member
Licensed User
Longtime User
Android 2.3.4 - Motorola Defy Plus - 32 GB - connected to PC via "Wi-Fi" and "B4A - Bridge"
0) install and open
1) connect menu
2) i choose the only device (external GPS antenna iBlue-747)
3) error: <Connection Error - Java.io.IOException: Device or resource busy>

Any Ideas ?
 

bluedude

Well-Known Member
Licensed User
Longtime User
Paired device

Hi,

My device is paired with my car bluetooth kit and when I step into my car (Audi) it automatically connects.

I was wondering if there is a way to monitor if it got connected when I enter my car. So I don't want to pair, connect etc. but basically just know when I'm in my car by monitoring to which device it connects.

Based on that information I can do a few cool things.

Cheers,
 

KY Leng

Member
Licensed User
Longtime User
Serial1.connect seem to response too slow

Hi Erel,

I have a bluetooth device using SPP (BT-SPP) and it is always ready for the connection with our phone. However, if I start using Serial1.connect
when the phone is not in the communication range with my BT-SPP,
the phone take about 20s to 1mn before telling us that it cannot connect to BT-SPP.

My question is:
1. How to cancel this connection before the serial'event raise?
or can we always cancel it with Serial1.diconnect?
2. How to shorten the response? I mean if our phone cannot connect to BT-SPP after 3s, we want to disconnect the BT...and then reconnect again. Normally, if the phone cannot fine the correspondant BT device in the range, it will keep searching in background and even we move in to the range, it still cannot connect proprely or cannot connect untill we reconnect it again.

All my questions are for : How to etablish a connection as fast as possible when the phone go into the corresponding BT range?

Looking forward to hearing from you soon, Erel.
 

Steven Goh

New Member
Licensed User
Longtime User
Serial reconnect error

Erel,

I just bought Basic4android and i am new. Downloaded the chat software and connects to my device (Bluetooth terminal) everything works fine.

The problem comes when i off the bluetooth device and the chat program jumps automaticly to "main" (AStream_Error)- which is correct.

I ON my bluetooth device and when i connect back again, it jumps to the chat page. When you try to chat (Send data to my bluetooth device), it will jump back again to "main" and pop up a "Connection is broken"... and it goes on and on.

It will only work fine again when i restart the chat application.

Is there a way to fix this? I am building a product base on bluetooth. Please help.
 
Last edited:

Steven Goh

New Member
Licensed User
Longtime User
Serial reconnect error

Problem solved.

Do it by using exitapplication - in which it actually kills the ChatActivity page but not the main. So application will automatically shows main.

Sub AStream_Error
ToastMessageShow("Connection is broken.", True)
ExitApplication
End Sub

Just to share
 

Steven Goh

New Member
Licensed User
Longtime User
Activity.Finish

Erel,

Thank you for your fast response. I am impressed with your great service. I have just changed to Activity.Finish.

Thanks again Erel.

Love Basic4android!! Its cool. :)
 
Last edited:

gawie007

Member
Licensed User
Longtime User
Bluetooth Pairing

Hi.
This all works quite well however I would like to pair devices and not have to scan for them again.

In Android developer you can query paired devices: Bluetooth | Android Developers

Is there a way to "getBondedDevices()" from the phone so that the devices can connect without having to be discoverable?

Kind regards

Gavin
 

gawie007

Member
Licensed User
Longtime User
I knew you were going to make it simple...
I was more concerned with Bluetooth and should have been looking at serial.
Apologies if I have wasted some of your time.
Thank you Erel!!!!!!!!
 

locxtronic

Member
Licensed User
Longtime User
B4X:
Sub Timer1_Tick
    If connected Then
        If TextReader1.Ready Then 'check if there is any data waiting to be read
            txtLog.Text = txtLog.Text & TextReader1.ReadLine & CRLF
            txtLog.SelectionStart = txtLog.Text.Length
        End If
    End If
End Sub
This code reads all text until it finds an end of line character (chr(10)). Maybe you are sending a string without an end of line character?

im using this code to read the data. but my app crash and force close displayed.
 

Similar Threads

  • Locked
  • Article
Android Tutorial Android JSON tutorial
Replies
90
Views
159K
  • Locked
  • Article
Android Tutorial SQL tutorial
Replies
161
Views
278K
  • Locked
  • Article
Android Tutorial GPS tutorial
Replies
310
Views
255K
Top