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

defillo

Member
Licensed User
Longtime User
Connection refused

Nothing to do, got the same message with a galaxy s mini and a htc desire when trying to connect to a PC bluetooth interface. SPP profile present on the pc.
when I try to connect (connect, connect2 and connect3) i've always the same reply, connection refused. devices correctly paired without any problem.
Any suggestion? from googleing I've seen this appears to be a common problem..
 

defillo

Member
Licensed User
Longtime User
as usual

tried also between the two devices, tried also with a windows mobile device, always same result: java.io.IOexception.connection refused
Windows mobile device instead connects to the PC smoothly..
 

moster67

Expert
Licensed User
Longtime User
Are you using a cooked ROM by any chance? Sometimes, these cooked ROMs introduce small bugs which are not present on the official ROM. Happened to me a few times when developing for Windows Mobile.

tried also between the two devices, tried also with a windows mobile device, always same result: java.io.IOexception.connection refused
Windows mobile device instead connects to the PC smoothly..
 

defillo

Member
Licensed User
Longtime User
no special rom

Absolutely standard devices, both with factory shipped rom. no success at all..
 

pinoy_ako

Member
Licensed User
Longtime User
hi erel.
i tried running your given sample, it worked ok. also changes the object position correctly if i change the orientation of my phone.

but when i make my new project, and copy paste everything from your sample, everthing is working the same as the sample except from two things, 1. i can send serial data. txtSend is being cleared when i press btnSend button. but no data is being sent out from my phone. 2. when i change the orientation of my phone, objects in my sample project is not placed correctly. unlike your sample.

pls. advice.

thanks
 

pinoy_ako

Member
Licensed User
Longtime User
ah ok. i just thought there will be settings i need to adjust in the IDE. i just tick the serial lib in the library tab, added 4 objects, renamed the objects, and selected all the codes from your sample and copy paste it to my new project. and i get a different response. thats bad.
 

pinoy_ako

Member
Licensed User
Longtime User
hi erel.
another question about changing the position of the object when my phone orientation is change. in your serial sample, object adjust automatically when orientation is change. but i dont see the code where it is done. sorry very noob question. where is it in the serial sample, the code that change the object position. i tried to add button on your serial sample. and when i change my phone orientation, the existing object change, but my additional button doesn't change position. pls. advise.

thanks
 

pinoy_ako

Member
Licensed User
Longtime User
yes erel. i downloaded the serial project you provided. that is why i was able to compare a new project to a program provided by you. and it seems that even if the codes are the same (codes that we are editing using B4A), the output is not the same.

does it mean that there are other things that i need to set erel?

if yes. can you give me that thing i need to set just to make my object change position when i change my orientation.
 
Last edited:

pinoy_ako

Member
Licensed User
Longtime User
now i did add. :D and the new project changes position now with change in orientation. thanks for that. :sign0098:
the serial tx/rx is now working also after i use your layout file.

i will try to figure out the difference on the two layouts. that is hard to do. :D

thanks erel.
 

defillo

Member
Licensed User
Longtime User
Still not solved the problem.
As I bought this compiler just to deal with BT data exchange, I feel really disappointed. the lack of support is also another reason to be disappointed. The documentation regarding the various modules is 'as poor as possible' just giving some examples. for sure I don't pretend (for the cost) that it's similar to visual studio but at least that it works. If i download apps from the market that works with BT serial connection, they works! so for sure it is not an hardware problem. At present time this whole thing is (for me) totally unuseful. (and I've bought also the update.. sigh..)
:sign0161:
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Still not solved the problem.
As I bought this compiler just to deal with BT data exchange, I feel really disappointed. the lack of support is also another reason to be disappointed. The documentation regarding the various modules is 'as poor as possible' just giving some examples. for sure I don't pretend (for the cost) that it's similar to visual studio but at least that it works. If i download apps from the market that works with BT serial connection, they works! so for sure it is not an hardware problem. At present time this whole thing is (for me) totally unuseful. (and I've bought also the update.. sigh..)
I'm sorry but I did my best to help you. I've tested the sample on several devices including HTC desire and it works fine.
Did you check the unfiltered logs for any other messages?
 

TomInAZ

New Member
Is there anyway to make serial via WiFi work easy? I am considering using one of the new XBee 802.11n shields with an Arduino Uno board, and will need a serial connection to make it work. Partly the reason I want to work with 802.11n is because I am not thrilled at the distance available with Bluetooth since it is only about 30 feet or less.
 

pinoy_ako

Member
Licensed User
Longtime User
I'm sorry but I did my best to help you. I've tested the sample on several devices including HTC desire and it works fine.
Did you check the unfiltered logs for any other messages?
true. i run the sample with htc desire and htc wildfire. the sample worked fine. :)
 

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
256K
Top