Android Question Bluetooth Error connecting : read failed, ......... read ret -1

Marco Maria Vilucchi

Active Member
Licensed User
Hi all,
I'm trying to connect my app with bluetooth and i'm studying the app of this tutorial: Android Bluetooth / BluetoothAdmin Tutorial

I installed the app "Bluetooth example" on my galaxy tab A, and I have paired with my galaxy note2
Then I press "search for device" button but even if the note2 is paired it can only be found if I make it visible to everyone.
I do it and the app "Bluetooth example" find it.
But when I try to connect the devices I have this error. read failed, socket might closed or timeout, read ret -1
The app is the same I downloaded. I didn't change anything.
How can I solve the connection error?
And hou can the App see the note2 devise without I make it visible to everyone? (They are paired)
Thanks all

After solved this problem I have other questions... but in other threads

Marco Maria Vilucchi

Active Member
Licensed User
I precise better.
I installed app "Bluetooth example" on my note2 and I want connect with my galaxy tab than doesn't have "Bluetooth example" for simulate a device bluetooth that my customer si building.
But I have the error: read failed, socket might closed or timeout, read ret -1

Marco Maria Vilucchi

Active Member
Licensed User
The example on both device works, but I need to connect my App with another device (non b4a).
I'm trying to connect example with my app (that contain BluetoohManager class).
I put into my app the MAC of the example device, make the example device discoverable and connect both devices. (it works)
But then if I send a message from example device, my app doesn't start "AStream_NewData".
Moreover CallSub2 never works.

Marco Maria Vilucchi

Active Member
Licensed User
I add my code.

On main module i add:

Sub Bottone_Click
    Dim device As NameAndMac
    device.Name = "MaMaVi"
    device.Mac = "34:31:11:4E:28:66"
End Sub
'BLUETOOTH ===========================================
Public Sub DiscoverFinished
    Log ("DiscoverFinished")
    If Starter.Manager.foundDevices.Size = 0 Then
        ToastMessageShow("No device found.", True)
        Dim l As List
        For Each nm As NameAndMac In Starter.Manager.foundDevices
        InputListAsync(l, "Choose device to connect", -1, True)
        Wait For InputList_Result (Index As Int)
        If Index <> DialogResponse.CANCEL Then
            Dim device As NameAndMac = Starter.Manager.foundDevices.Get(Index)
            ProgressDialogShow2($"Trying to connect to: ${device.Name} (${device.Mac})"$, False)
        End If
    End If
End Sub

Public Sub AfterConnect (Success As Boolean)
End Sub

Sub btnSearchForDevices
    Log ("btnSearchForDevices")
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    If Result = False Then
        ToastMessageShow("No permission...", False)
    End If
    Dim success As Boolean = Starter.Manager.SearchForDevices
    If success = False Then
        ToastMessageShow("Error starting discovery process.", True)
        ProgressDialogShow2("Searching for devices...", False)
    End If
End Sub
'FINE BLUETOOTH ===========================================
Then I add BluetoohManager class modified for my app

Sub Class_Globals
    Private AStream As AsyncStreams
    Private serial As Serial
    Private admin As BluetoothAdmin
    Public foundDevices As List
    Type NameAndMac (Name As String, Mac As String)
    Public BluetoothState, ConnectionState As Boolean
End Sub

Public Sub Initialize
    If admin.IsEnabled = False Then
        If admin.Enable = False Then
            ToastMessageShow("Error enabling Bluetooth adapter.", True)
            ToastMessageShow("Enabling Bluetooth adapter...", False)
        End If
        BluetoothState = True
    End If
End Sub

Private Sub Admin_StateChanged (NewState As Int, OldState As Int)
    Log("state changed: " & NewState)
    BluetoothState = NewState = admin.STATE_ON
End Sub

Public Sub ConnectTo (Device As NameAndMac)
End Sub

Private Sub Serial_Connected (Success As Boolean)
    Log("connected: " & Success)
    CallSub2(Main, "AfterConnect", Success) 'allow the activity to hide the progress dialog
    ConnectionState = Success
    If Success = False Then
        ToastMessageShow("Error connecting: " & LastException.Message, True)
        Log(" " & serial.Name & " serial.address " & serial.Address)
        If AStream.IsInitialized Then AStream.Close
        'prefix mode! Change to non-prefix mode if communicating with non-B4X device.
        AStream.InitializePrefix(serial.InputStream, False, serial.OutputStream, "astream")
'        Dim ms As String = "prova"
'        AStream.Write(ms.GetBytes("utf8"))

'        StartActivity(ChatActivity)
    End If
End Sub

Public Sub SendMessage (msg As String)
End Sub

Private Sub AStream_NewData (Buffer() As Byte)
    CallSub2(GestisciSensori, "NewMessage", BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
End Sub

Private Sub AStream_Error
    ToastMessageShow("Connection is broken.", True)
    ConnectionState = False
End Sub

Private Sub AStream_Terminated
End Sub

Public Sub Disconnect
    If AStream.IsInitialized Then AStream.Close
End Sub

Public Sub SearchForDevices As Boolean
    Return admin.StartDiscovery
End Sub

Private Sub Admin_DiscoveryFinished
    CallSub(Main, "DiscoverFinished")
End Sub

Private Sub Admin_DeviceFound (Name As String, MacAddress As String)
    Log(Name & ":" & MacAddress)
    Dim nm As NameAndMac
    nm.Name = Name
    nm.Mac = MacAddress
End Sub

Public Sub ListenForConnections
    'this intent makes the device discoverable for 300 seconds.
    Log ("ListenForConnections")
    Dim i As Intent
    i.Initialize("android.bluetooth.adapter.action.REQUEST_DISCOVERABLE", "")
    i.PutExtra("android.bluetooth.adapter.extra.DISCOVERABLE_DURATION", 300)
End Sub

Private Sub NotifyOfStateChanged
'    For Each Target In Array(Main, ChatActivity)
'        CallSub(Target, "UpdateState")
'    Next
End Sub
This is the code of GestisciSensori called by AStream_NewData, but AStream_NewData doesn't start

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:

End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Public Sub NewMessage (msg As String)
    Log("msg" & msg)
' Qui stabilisco il sensore chiamante e faccio udate della tabella misurazioni sul valore opportuno
'    i primi due caratteri del messaggio possono essere il sensore
End Sub
On example device i send a message, but my app don't receive it