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

eshaulx

New Member
Licensed User
Longtime User
Not receving any data

Dear Basic4Android guys,

I'm trying to receive a communication from a bluetooth device that I have built.
The communication it's sending is: chr(170) which is "AA" every second.
I used this tutorial, I managed to find the device, but I did not receive any data from it. quick debugging turning out that TextReader1.Ready is never ready.

What am i missing in order to receive the data?
I'm not attaching any code because i am using your tutorial code as is.

Best,
Erez.
 

wm.chatman

Well-Known Member
Licensed User
Longtime User
Dir Erel

I have been reading and working with the Android Serial tutorial. I am a bit slow at understanding how this could be used, to gain access to external Gps.
Is it possible for you to help with a example for connecting to a external Gps Android Serial tutorial using the Asnyc Streams please. :sign0085:

The Samsung galaxy SII works great with a external BT device. No problems there at all.

Thank you much Erel
Best regards
William
 

wm.chatman

Well-Known Member
Licensed User
Longtime User
Thank you Erel for your lightning support.

Are you talking about this section?

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
txtLog.Width = 100%x
End Sub

Change the InitializePrefix to Initialize? I dont get it Erel :-(
 
Last edited:

wm.chatman

Well-Known Member
Licensed User
Longtime User
OK Erel, hate to bug you again. I am trying to get this to work.

Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("2")
If AStream.IsInitialized = False Then
'AStream.InitializePrefix(Main.serial1.InputStream, True, Main.serial1.OutputStream, "AStream")
AStream.Initialize(In As java.io.InputStream,Out As java.io_OutputStream, Eventname As String)
End If
txtLog.Width = 100%x
End Sub

at this time it gives me a error msg compiling, I know I am missing something.?

What I do not understand is this.
The Output Stream that is used for writing data. Pass Null if you only want to read with this object.?
What's up with the Pass Null?
We are only reading with this object, and not writing. So, what did I not do right here? Please let me know.

@ Erel. please forgive me, Please do not post questions in this sub-forum. < I missed this. Feel free to move post.
 
Last edited:

wm.chatman

Well-Known Member
Licensed User
Longtime User
By Gosch... I got it. and sure work's now.
It took some time to check this out, but some times thing's go slow and other times faster then usual. :eek:
That's how it is, if you work on four things at once.

> AStream.Initialize(Main.Serial1.InputStream, Main.Serial1.OutputStream, "AStream") <

Sorry I had also postet here a few Questions.
@ Erel > Thank you for your help and not getting teed at me. :)

Now to the next step. Oh, if need be, do move this Thread into the right area.

But also I see the You, You, You with the sentances.?

Best regards to all.
William
 

benkly

New Member
Licensed User
Longtime User
Hello,

I only need to send some decimal numbers without any control signs to a bluetooth device. Would this be possible?
And something I don't get out of the example code, if I build up a connection to a BT device, in this case a BT-to-Serial device, where do I change the COM specific things like the BAUD rate and so on?

Regards, Benny.
 

raphaelcno

Active Member
Licensed User
Longtime User
Hello,
And something I don't get out of the example code, if I build up a connection to a BT device, in this case a BT-to-Serial device, where do I change the COM specific things like the BAUD rate and so on?

You don't have to specify COM settings for the Bluetooth connection itself. The COM settings apply only to the serial connection (DB9 port), and you change them by connecting the BT/Serial device to a PC with terminal software.
 

SergioAntunes

Member
Licensed User
Longtime User
I tried the serial example App with the following:
1. Windows 7 64 running a copy of Real Term,
2. Compiled the Bluetooth.b4a app to a Samsung SCH-1500 cell phone,

I am able to send characters from the Samsung to Realterm on Windows however, when I send any thing from Realterm to the Samsung Bluetooth.b4a terminates.

Any suggestions where I should look for the problem. My guess is that it has something to do with the Bluetooth driver under Windows 7?

Notes:
1. I connect with B4A bridge over Bluetooth without any issues,
2. I can transfer files in both direction over Bluetooth.

Thanks
 

SergioAntunes

Member
Licensed User
Longtime User
Connecting to a Bluetooth serial adapter from an Android 4.0.3 Galaxy II.

I developed an App using the Serial library that talked to a device over Bluetooth. The App was running OK on a Samsung SCH1500 cell phone (with Android version 2.3.5. The Bluetooth to Serial adapter I used was from USConverters model UCBT232B.

I just purchased a Samsung Galaxy II pad with Android 4.0.3. Download B4A-Bridge and installed my App. The problem I have is that when I attempt the serial.connect I keep on getting the screen to enter the pin number as if the Bluetooth device was not paired. I did pair the device prior running the App.

I am trying to look at the log files.

Any ideas?

Thanks.
 

SergioAntunes

Member
Licensed User
Longtime User
Do you see the device in the paired devices list? Does it show when you call GetPairedDevices?

Yes the device appears on the list.

The problem might be in the adapter. Maybe you need to reset it somehow before pairing with a new device.

I have reset the device a couple of times. When running on the phone when the app tries to connect it displays the PIN screen and accepts the pin when entered. On the new Galaxy, it takes the PIN but fails to connect.
 

Similar Threads

  • Locked
  • Article
Android Tutorial Android JSON tutorial
Replies
90
Views
164K
  • Locked
  • Article
Android Tutorial SQL tutorial
Replies
161
Views
284K
  • Locked
  • Article
Android Tutorial GPS tutorial
Replies
310
Views
263K
Top