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

KitCarlson

Active Member
Licensed User
Longtime User
It seems like you are reinventing the wheel. Why not try a BT OBD2 interface and the Torque program on your phone from google play, no need for Arduino.

Back to the original question:
Most BT modules interface via a UART, SPI, I2C, or 8 bit bus. OBD2 interfaces often use an elm327 chip. It is well documented, so you can get setup and command information from data sheet. It is always helpful to use a protocol analyzer like Saleae Logic to monitor comunications in development. I have not done the OBD2, but have done BT to ATmega128 chip on my own ECU. B4A is a great development tool on the Android side. I also plan B4J for PC app.
 
Last edited:

Dogbonesix

Active Member
Licensed User
Longtime User
Thanks. Lots of information that I needed. I will try the BT ODB2. My plans are of a wider scope and I am looking for a general experience. I collaborate with various groups of people (mostly medical) that are interested in Wellness - that includes in home diagnostics. The Arduino seems to be the prime device to gather, display and distribute the data that might be gathered. I don't have the urgency - that maybe I should have - so I am off to some tangent that I understand and can then utilize in other projects. I will post any successes but probably a lot question prior - thanks for the insight.
 

Kevin L. Johnson

Member
Licensed User
Longtime User
Hello all,

I am using the improved version of Erel's Serial Tutorial and have rolled the capability into my apps code where I am communicating with an external Inertial Measurement Unit (IMU) which in theory, should be more accurate than the phones internal sensors providing roll, pitch and yaw orientation.

My question is ... is there an alternative to having to connect and pair to the external bluetooth IMU each and every time I run the software, as it takes up considerable time.

I was hoping that I could do it once and then run the software several times without needing to reconnect.

Thanks in advance ...
Kevin
 

Martin Larsen

Active Member
Licensed User
Longtime User
This works almost with my arduino and a bluetooth module. I use normale initialize instead of the prefix mode.

The problem is that my arduino code expects a carriage return after each command I send to it from my phone.

I have tried the following but it won't compile:

AStream.Write(txtInput.Text.GetBytes("UTF8") & chr(13))

How can I add a CR?
 

NeoTechni

Well-Known Member
Licensed User
Longtime User
Txtinput.text = txtinput.text & chr(13)
AStream.Write(txtInput.Text.GetBytes("UTF8") )

?
 

Mitesh_Shah

Member
Licensed User
Longtime User
HI DavideV

Thanks For Replay. i make Android apps to control Relay's via BT Module its' working perfectly in android 4.0.4 (Samsung) but i test in other phone OS 4.4.2 kitkat(Micro Max) it's not connect with BT Module. i used B4A 2.71

Mitesh
 

DavideV

Active Member
Licensed User
Longtime User
HI DavideV

Thanks For Replay. i make Android apps to control Relay's via BT Module its' working perfectly in android 4.0.4 (Samsung) but i test in other phone OS 4.4.2 kitkat(Micro Max) it's not connect with BT Module. i used B4A 2.71

Mitesh

maybe a problem with that phone?
i tested with LG G2 mini 4.4.2 and S4mini with custom rom cyanogenmod 4.4.4 both working perfect with the BT module .

Edit: try to unpair the devices then pair again and check if it's working now...
 
Last edited:

Mitesh_Shah

Member
Licensed User
Longtime User
HI DavideV

i will Try with some Different BT Module but, SAM problem, my apps show msg >> searching for Device (1 Divice found)

but Not Connect with that

Regard

Mitesh
 

GMan

Well-Known Member
Licensed User
Longtime User
Did you setup the BT Modules first ?
Most of them are pre-configured for low baudrates, so you have to set it to 115200 ON THE BT-Module
 

DavideV

Active Member
Licensed User
Longtime User
Hi, try to pair the module(s) directly from settings>bluetooth> search devices instead of using your app. Then you should see it (them) listed in your app ( if your app provides a list of paired devices)
The baudrate isn't relevant for the bluetooth connection and pairing since it is the data speed between the module and the connected microprocessor you are using.
The bluetooth speed is handshaked by the radio side of the module and the phone's bluetooth radio and cannot be modified.

Screenshot_2015-01-05-16-27-51.png
 

rzv25

Member
Licensed User
Longtime User
Hello,
I need to acces the bluetooth services from more than one activity, so I created a code module where I put the bluetooth code:


B4X:
Sub Process_Globals
    Dim serial1 As Serial
    Dim admin As BluetoothAdmin
End Sub

Sub Init
  admin.Initialize("admin")
  serial1.Initialize("serial1")
End Sub

Sub ConnectToDevice(strBtDeviceName As String, strBtDeviceMac As String, idInitiatingActivity As Int)
  serial1.Connect(strBtDeviceMac)
  ProgressDialogShow ("Connecting to Bluetooth device " & strBtDeviceName & " ...")
  strConnectingBtDeviceName = strBtDeviceName
  strConnectingBtDeviceMac  = strBtDeviceMac
  InitiatingActivity = idInitiatingActivity
End Sub


Sub serial1_Connected (Success As Boolean)
  If Success = False Then
  bBtConnected = False
  ToastMessageShow("Error connecting to Bluetooth device '" & strConnectingBtDeviceName & "'.", True)
  If InitiatingActivity = INITIATED_BY_MAIN_ACTIVITY Then
  CallSubDelayed2(Main, "App_ConnectionStateChanged", False)
  end if
  Else
  bBtConnected = True
     'Make the newly paired device the default one
     strBtDefaultDeviceMac = strConnectingBtDeviceMac
     'Inform that the currently connected device is the newly paired one
     strBtConnectedDeviceMac = strConnectingBtDeviceMac
    
  If InitiatingActivity = INITIATED_BY_MAIN_ACTIVITY Then
  CallSubDelayed2(Main, "App_ConnectionStateChanged", True)
  Else If InitiatingActivity = INITIATED_BY_SETTINGS_BT_ACTIVITY Then
  CallSubDelayed(Settings_Bluetooth, "NewDeviceConnected")
  End If
  If AStream.IsInitialized = False Then
  AStream.Initialize(serial1.InputStream, serial1.OutputStream, "AStreams")
  End If
  End If
  ProgressDialogHide
End Sub

Init function is called from the 'Activity_Create' function from 'Main' activity. 'ConnectToDevice' function is called either from the 'Main' activity or from 'Settings_Bluetooth' activity.

I read that code modules cannot catch events. So my question is where should I put the code of 'serial1_Connected' ? Should I add this event in both activities and eventually call from there one common function that is placed in my code module ?
Thank you
 
Last edited:
Status
Not open for further replies.
Top