1. *** New version of B4J is available ***
    B4J v7.8
    Dismiss Notice

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

Discussion in 'Android Questions' started by Marco Maria Vilucchi, Jun 5, 2019.

  1. Marco Maria Vilucchi

    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.
    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
     
  2. Marco Maria Vilucchi

    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:
    java.io:IOEException: read failed, socket might closed or timeout, read ret -1
     
  3. Erel

    Erel Administrator Staff Member Licensed User

    In order to create a SPP Bluetooth connection the other device must be listening for such connections. Run the example on both devices.
     
  4. Marco Maria Vilucchi

    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".
    Why?
    Moreover CallSub2 never works.
     
  5. Erel

    Erel Administrator Staff Member Licensed User

    Make sure not to use prefix mode in that case.

    You are doing a mistake somewhere. That is all that I can say from the information you provided.
     
  6. Marco Maria Vilucchi

    Marco Maria Vilucchi Active Member Licensed User

    Sorry...
    I add my code.

    On main module i add:

    Code:
    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", -1True)
            
    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

    Code:
    Sub Class_Globals
        
    Private AStream As AsyncStreams
        
    Private serial As Serial
        
    Private admin As BluetoothAdmin
        
    Public foundDevices As List
        
    Type NameAndMac (Name As StringMac 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, Falseserial.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

    Code:
    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
     
  7. Erel

    Erel Administrator Staff Member Licensed User

    Code:
    'prefix mode! Change to non-prefix mode if communicating with non-B4X device.
            AStream.InitializePrefix(serial.InputStream, Falseserial.OutputStream, "astream")
     
  8. Marco Maria Vilucchi

    Marco Maria Vilucchi Active Member Licensed User

    My app is b4x
     
  9. Erel

    Erel Administrator Staff Member Licensed User

    What are you communicating with? An Android device running your B4A app?
     
  10. Marco Maria Vilucchi

    Marco Maria Vilucchi Active Member Licensed User

    anyway I tried to use AStream.Initialize and I receive the message, but bluetooh example no longer receive messages
     
  11. Marco Maria Vilucchi

    Marco Maria Vilucchi Active Member Licensed User

    In the future i'll use a non b4x device. Now I'm trying with a note2 (with bluetooth example) and a galaxy teb (with my B4A app)
     
  12. Erel

    Erel Administrator Staff Member Licensed User

Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice