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

Marco Maria Vilucchi

Active Member
Licensed User
Longtime 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.
java.io:IOEException: 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
Marcom

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

Marco Maria Vilucchi

Active Member
Licensed User
Longtime 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:
java.io:IOEException: read failed, socket might closed or timeout, read ret -1
 
Upvote 0

Marco Maria Vilucchi

Active Member
Licensed User
Longtime 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".
Why?
Moreover CallSub2 never works.
 
Upvote 0

Marco Maria Vilucchi

Active Member
Licensed User
Longtime User
Sorry...
I add my code.

On main module i add:

B4X:
Sub Bottone_Click
    Starter.Manager.ListenForConnections
    Dim device As NameAndMac
    device.Name = "MaMaVi"
    device.Mac = "34:31:11:4E:28:66"
    Starter.Manager.ConnectTo(device)
    StartActivity(Accesso)
End Sub
'BLUETOOTH ===========================================
Public Sub DiscoverFinished
    Log ("DiscoverFinished")
    ProgressDialogHide
    If Starter.Manager.foundDevices.Size = 0 Then
        ToastMessageShow("No device found.", True)
    Else
        Dim l As List
        l.Initialize
        For Each nm As NameAndMac In Starter.Manager.foundDevices
            l.Add(nm.Name)
        Next
        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)
            Starter.Manager.ConnectTo(device)
            ProgressDialogShow2($"Trying to connect to: ${device.Name} (${device.Mac})"$, False)
        End If
    End If
End Sub

Public Sub AfterConnect (Success As Boolean)
    ProgressDialogHide
End Sub

Sub btnSearchForDevices
    Log ("btnSearchForDevices")
    rp.CheckAndRequest(rp.PERMISSION_ACCESS_COARSE_LOCATION)
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    If Result = False Then
        ToastMessageShow("No permission...", False)
        Return
    End If
    Dim success As Boolean = Starter.Manager.SearchForDevices
    If success = False Then
        ToastMessageShow("Error starting discovery process.", True)
    Else
        ProgressDialogShow2("Searching for devices...", False)
    End If
End Sub
'FINE BLUETOOTH ===========================================

Then I add BluetoohManager class modified for my app

B4X:
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
    admin.Initialize("admin")
    serial.Initialize("serial")
    If admin.IsEnabled = False Then
        If admin.Enable = False Then
            ToastMessageShow("Error enabling Bluetooth adapter.", True)
        Else
            ToastMessageShow("Enabling Bluetooth adapter...", False)
        End If
    Else
        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
    NotifyOfStateChanged
End Sub



Public Sub ConnectTo (Device As NameAndMac)
    serial.Connect(Device.Mac)
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
        Log(LastException.Message)
        ToastMessageShow("Error connecting: " & LastException.Message, True)
    Else
        Log("serial.name " & 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
    NotifyOfStateChanged
End Sub

Public Sub SendMessage (msg As String)
    AStream.Write(msg.GetBytes("utf8"))
End Sub

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

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

Private Sub AStream_Terminated
    AStream_Error
End Sub

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

Public Sub SearchForDevices As Boolean
    foundDevices.Initialize
    Return admin.StartDiscovery
End Sub

Private Sub Admin_DiscoveryFinished
    Log("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
    foundDevices.Add(nm)
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)
    StartActivity(i)
    serial.Listen
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

B4X:
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:
    'Activity.LoadLayout("Layout1")

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
 
Upvote 0
Top