B4J Question jBluetooth Pairing

walterf25

Expert
Licensed User
Longtime User
Hello everyone, i have written an app which searches for a certain device UID, I have a B4A app running on a device which is running Android 8.0 which basically just listens when the B4J app tries to connect, I followed @Erel 's tutorial here, My question is this, everything seems to work only when I pair the devices manually through the Bluetooth Settings from the Android device, is there a way to automatically have both my Laptop and Android device pair automatically?

here is the B4J Code:
B4X:
Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.SetFormStyle("UNIFIED")
    MainForm.RootPane.LoadLayout("main") 'Load the layout file.
    MainForm.Show
    
    MainForm.Title = "Hermosa Temp Tester"
    
    lblConnection.Text = "Disconnected"
    
    foundDevices.Initialize
    bt.Initialize("bt")
    If bt.IsEnabled Then
        bt.Listen2("0000FE45-0000-1000-8000-00805F9B34FB")
    End If
End Sub

'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub btnSearch_Click
    Dim res As Boolean = bt.StartDiscovery
    If res Then
        searchingfordevices = True
        lv1.Items.Clear
        ''UpdateState
    Else
        Log("Error starting discovery")
    End If
End Sub

Sub btnConnect_Click
    Dim address As String = foundDevices.Get(lv1.SelectedItem)
    Log("connecting to: " & address)
    bt.Connect(address)
End Sub

#Region Bluetooth Functions
Sub bt_DeviceFound (Name As String, MacAddress As String)
    Dim description As String = Name & ": " & MacAddress
    lv1.Items.Add(description)
    foundDevices.Put(description, MacAddress)
End Sub

Sub bt_Connected (Success As Boolean, Connection As BluetoothConnection)
    Log($"Connected, success=${Success}"$)
    If Success Then
        currentconnection = Connection
        connected = True
        lblConnection.Text = "Connected to: " & Connection.Name
        If astream.IsInitialized Then astream.Close
        astream.InitializePrefix(Connection.InputStream, True, Connection.OutputStream, "AStream")
    End If
    bt.Listen
End Sub

And Here's the relevant code from the B4A app, i have the code running in a Service.
B4X:
Sub Service_Create
    Dim n As Notification
    n.Initialize
    n.SetInfo("TempTester", "Hermosa Temp Tester", Main)
    Service.StartForeground(1, n)
    
        admin.Initialize("admin")
        serial1.Initialize("serial1")
        foundDevices.Initialize
    
    Dim i As Intent
    i.Initialize("android.bluetooth.adapter.action.REQUEST_DISCOVERABLE", "")
    i.PutExtra("android.bluetooth.adapter.extra.DISCOVERABLE_DURATION", 300)
    StartActivity(i)
    
    ph.Initialize("ph")
    
    If admin.IsEnabled = False Then
        If admin.Enable = False Then
            ToastMessageShow("Error enabling Bluetooth adapter.", True)
        Else
            ToastMessageShow("Enabling Bluetooth adapter...", False)
            'the StateChanged event will be soon raised
        End If
    Else
        ''Admin_StateChanged(admin.STATE_ON, 0)
    End If
    
    serial1.Listen
End Sub

Sub Service_Start (StartingIntent As Intent)
    
    Service.StopAutomaticForeground 'Call this when the background task completes (if there is one)
End Sub

Sub Service_Destroy

End Sub

Sub StartDiscovery
    If admin.StartDiscovery    = False Then
        ToastMessageShow("Error starting discovery process.", True)
    Else
        ''ProgressDialogShow("Searching for devices...")
        CallSubDelayed(Main, "showDevices")
    End If
End Sub

Sub Admin_DiscoveryFinished
    ProgressDialogHide
    If foundDevices.Size = 0 Then
        ToastMessageShow("No device found.", True)
    Else
        Dim l As List
        l.Initialize
        For i = 0 To foundDevices.Size - 1
            Dim nm As NameAndMac
            nm = foundDevices.Get(i)
            l.Add(nm.Name)
        Next
        CallSubDelayed3(Main, "ShowDevicesFound", l, foundDevices)
    End If
End Sub


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)
    ''ProgressDialogShow("Searching for devices (~ device found)...".Replace("~", foundDevices.Size))
    CallSubDelayed2(Main, "AddDevices", "Searching for devices ( ~ device found)...".Replace("~", foundDevices.Size))
End Sub

Sub Connect(mac As String)
    serial1.Connect(mac)
End Sub

Sub astream_NewData (Buffer() As Byte)
    
End Sub

Sub astream_Terminated
    LogColor("astreams terminated", Colors.Red)
End Sub

Sub astream_Error
    LogColor("astreams error", Colors.Red)
    astream.Close
    serial1.Disconnect
    connected = False
End Sub

Sub serial1_Connected (Success As Boolean)
    LogColor("connection succesful: " & Success, Colors.Blue)
    If Success Then
        connected = True
        If astream.IsInitialized = False Then
            astream.InitializePrefix(serial1.InputStream, True, serial1.OutputStream, "AStream")
        End If
        ProgressDialogHide
    Else
        ProgressDialogHide
        LogColor("connection failed", Colors.Red)
    End If

End Sub

Does anyone know if it's possible to pair to a device without manually having to do it?

Thanks,
Walter
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…