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

Roberto P.

Well-Known Member
Licensed User
Longtime User
I have a bar code reader that works regularly, but that the sample application can not see what can be?
anyone can help me.
thanks
 

Roberto P.

Well-Known Member
Licensed User
Longtime User
hello Erel
yes, I have enabled this feature SPP, but I get error shown in the picture
 

Attachments

  • error.png
    error.png
    54.1 KB · Views: 485
  • error2.png
    error2.png
    55.8 KB · Views: 508

Roberto P.

Well-Known Member
Licensed User
Longtime User
the problem was the "suffix" mode of the barcode reader.
thank you
 

praktikant

Member
Licensed User
Longtime User
Hey Erel,
is there some way to make the connection to a device faster?
The program search for devices 12 seconds. Maybe you know a way to make it faster?

Best regards
 

tango

Member
Licensed User
Longtime User
hi erel,
i tested bluetooth sample with astream and bluetooth RFID. it is ok. but if i power off RFID and then Power on RFID again, it is not work. So how can i control rfid in a timer and if not enable reload initializing procedure

thanks
 

walterf25

Expert
Licensed User
Longtime User

jahswant

Well-Known Member
Licensed User
Longtime User
Is there a way to autoconnect to a specific Bluetooth device when i reach near it and send data to it without any intervention ?
 

jahswant

Well-Known Member
Licensed User
Longtime User
I'm knocking my head on this issue since 2 days I'm tired i will show my service code for annotations...

B4X:
#Region  Service Attributes
    #StartAtBoot: False
    #StartCommandReturnValue: android.app.Service.START_STICKY 
#End Region

Sub Process_Globals
   Dim BT As BluetoothAdmin
   Dim Serial1 As Serial
   Dim btConnected As Boolean
   Private ast As AsyncStreamsText
   Dim MyDeviceName As String 
   Dim Notification1 As Notification
   Dim ServiceMessage As String
   Dim TT As Timer
End Sub
Sub Service_Create
   TT.Initialize("TT",1000)
    MyDeviceName = "ALCATEL ONE TOUCH POP7"  'Put the name of your coupled device here!
   'MyDeviceName = "BlueTooth Printer"
   ToastMessageShow("Trying to connect to " & MyDeviceName, True)
 
   Try
      BT.Initialize("BT")
      Serial1.Initialize("Serial1")
    
   Catch
      ToastMessageShow("No BlueTooth Device visible...", True)
   End Try
     
          'Start Bluetooth
      Try
         If BT.IsEnabled = False Then
            BT.Enable
           
         Else
            'connect to device
            BTConnectToDevice
             
         End If
      Catch
      Log(LastException.Message)
      End Try

    Notification1.Initialize
    Notification1.Icon = "icon" 'use the application icon file for the notification
End Sub

Sub Service_Start (StartingIntent As Intent)
    ServiceMessage="Watch Application"
    Notification1.SetInfo(ServiceMessage, "Is Running" , Main)
    Notification1.Sound = False
    'Make sure that the process is not killed during the download
    'This is important if the download is expected to be long.
    'This will also show the status bar notification
    Service.StartForeground(1, Notification1)
    Log("service running")
End Sub

Sub Service_Destroy

End Sub

Sub BT_StateChanged(NewState As Int,OldState As Int)
   Try
   If NewState = BT.STATE_ON Then
      BTConnectToDevice
      Log("BT Connecting")
   Else
      Serial1.Disconnect
      btConnected = False
      Log("BT Disconnecting")
   End If
   Catch
   Log(LastException.Message)
   End Try
End Sub
Sub BTConnectToDevice
   Dim PairedDevices As Map
 
   PairedDevices = Serial1.GetPairedDevices
   Try
      Serial1.Connect3(PairedDevices.Get(MyDeviceName),1)
   Catch
      ToastMessageShow("Device not available",True)
   End Try
End Sub

Sub Serial1_Connected (Success As Boolean)
  Try
   If Success = True Then
      ToastMessageShow("Bluetooth connected to " & Serial1.Address, False)
     If ast.IsInitialized = False Then
        ast.Initialize(Me, "ast", Serial1.InputStream, Serial1.OutputStream)
    End If
    Log("BT Connected")
    SendCommand("OPEN DOOR")
    Log("Sent")
     ToastMessageShow(""&btConnected,True)
   Else   'disconnected
    
      ToastMessageShow("Connection to " & Serial1.Address &" broken!", True)
      btConnected = False
      ToastMessageShow(""&btConnected,True)
   End If
   Catch
      ToastMessageShow("Device not available",True)
   End Try
End Sub
Sub ast_Terminated
Try
ToastMessageShow("Connection is broken.", True)
ast_Error
Catch
      ToastMessageShow("Device not available",True)
End Try
End Sub
Sub TT_Tick

End Sub
Sub ast_Error
   Try
   ToastMessageShow("Connection is broken.", True)
   If btConnected = False Then
    Log(DateTime.Time(DateTime.Now)&": Service_Start")
    Dim r As Int = Rnd(100,200)
    Log(DateTime.Time(DateTime.Now)&": random="&r)
    StartServiceAt("", DateTime.Now + 2 * 100, False)
    'StopService("")
    Else
    Return
    End If
    Catch
      ToastMessageShow("Device not available",True)
   End Try
End Sub

With this i'm able to reconnect if turn BT on/off buth is leave discovery area and come back i'm not able to reconnect.Just advices and i will achieve it...
 

slavatzap

New Member
Hello,
I have an arduino controller and a makeblock ble bluethooth item and I want to connect between them.
I tried your code on my Nexus 5 but when I try to connect I get this error :
>java.io.IOException: read failed, socket might closed or timeout, read ret: -1​
or if I make the item comptaible with my nexus then when I try search for devices it wont find my item.
how can i Fix this?
 

Scantech

Well-Known Member
Licensed User
Longtime User
There seems to be an issue with searching functions. When I run search for device, it will find over 10 non existing devices with blank names return and the 2 devices that are available is shown in the list. A bug?
 

DavideV

Active Member
Licensed User
Longtime User
@Scantech :
if there are non-paired device near you the OS will report them and, slowly, the name will appear...
You should see the same behaviour searching devices with the native bluetooth setting app
 
Status
Not open for further replies.
Top