Android Question receive bluetooth string with variable lenght

Regis44

Member
Licensed User
Longtime User
Hello, first my apologies if the answer is already post.

I want to receive a string by bluetooth but the length of my emitted string is never the same. So the buffer never contains all the received datas at the same time.

So I want to receive datas since the detection of the CR/LF characters at the end of the string.

I tried different things based on the examples found on this forum and the web with no success.

Thank you for your help.

Régis.
 

Regis44

Member
Licensed User
Longtime User
Thank you very much for your quick answer.It works great. I followed this example : http://www.b4x.com/android/forum/th...orking-with-streams-of-text.27002/#post156325.

Below my code if someone else is interested.

B4X:
Sub Process_Globals
  DimadminAsBluetoothAdmin
  Dimserial1AsSerial
  PrivateastAsAsyncStreamsText
End Sub

Sub Globals
End Sub

Sub Activity_Create(FirstTime As Boolean)
  If FirstTime Then
   admin.Initialize("admin")
   serial1.Initialize("serial1")
  EndIf
  Activity.LoadLayout("gyropode")
  Activity.AddMenuItem2("Connect device","Menu",LoadBitmap(File.DirAssets,"bluetooth.png"))
  Activity.Title="App - Disconnected"
End Sub

Sub Activity_Resume
  If admin.IsEnabled = False Then
    If admin.Enable = False Then
      ToastMessageShow("Error enabling Bluetooth adapter.", True)
    Else
      ToastMessageShow("Enabling Bluetooth adapter...", False)
    EndIf
  Else
    Admin_StateChanged(admin.STATE_ON, 0)
  EndIf
End Sub

Sub Admin_StateChanged (NewState As Int, OldState As Int)
End Sub

Sub Activity_Pause (UserClosed As Boolean)
  If UserClosed = True Then
    serial1.Disconnect
    Activity.Title="App - Disconnected"
  EndIf
End Sub

Sub Menu_Click
  SelectSender
    Case"Connect device"
    Dim PairedDevices As Map
    PairedDevices = serial1.GetPairedDevices
    Dim l As List
    l.Initialize
    For k = 0 To PairedDevices.Size - 1
       l.Add(PairedDevices.GetKeyAt(k))
    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 and connect
    EndIf
  EndSelect
End Sub

Sub Serial1_Connected (Successful As Boolean)
  ProgressDialogHide
  Log("connected: " & Successful)
  If Successful Then
    If ast.IsInitialized Then ast.Close
    ast.Initialize(Me, "ast", serial1.InputStream, serial1.OutputStream) 'initialize AsyncStreamsText with the socket streams.
    Activity.Title="App - Connected"
  Else
    Log(LastException)
    ToastMessageShow("Connection error.", True)
  EndIf
End Sub

Sub ast_NewText(Text As String)
  Log(Text)
  Log(Text.Length)
End Sub

Sub ast_Terminated
  Log("Connection terminated")
End Sub

Sub AStream_Error
  ToastMessageShow("Connection is broken.", True)
  Activity.Title="App - Disconnected"
End Sub
 
Upvote 0
Top