Android Question Work with a new example Bluetooth

red30

Well-Known Member
Licensed User
Longtime User
Why does Bluetooth turn on when the program just opens? Is it possible to make "turn on Bluetooth?” Dialog when I click on the btnSearchForDevices button? if the user pushes "yes", the search process starts, otherwise nothing is happening. I do not understand how to do this for this new example. Another question is whether it is possible to add a new device to the list as soon as it is found and then to keep on searching and adding to the list as new devices appear?
B4X:
#Region  Project Attributes
    #ApplicationLabel: Test
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: False
#End Region

#AdditionalJar: com.android.support:support-v4

Sub Process_Globals
    'Public Manager As BluetoothManager
    Private rp As RuntimePermissions
    Dim loc As AHLocale
End Sub

Sub Globals
    Private btnSearchForDevices As Button
    Private btnexit As Button
    Private sonLang As Spinner
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
End Sub

Sub Activity_Resume
    'UpdateState
End Sub

Public Sub UpdateState
    If Starter.Manager.BluetoothState=True Then
        'UpdateState

        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
        If Result = False Then
            ToastMessageShow("Нет разрешения...", False)
            Return
        End If
        Dim success As Boolean = Starter.Manager.SearchForDevices
        If success = False Then
            ToastMessageShow("Ошибка запуска процесса поиска.", True)
        Else
            ProgressDialogShow2("Поиск утройств...", False)
        End If
    End If
    'btnSearchForDevices.Enabled = Starter.Manager.BluetoothState
End Sub

Sub Activity_Pause (UserClosed As Boolean)
  
End Sub

Sub btnSearchForDevices_Click
    StartService(Starter)
    UpdateState
End Sub

Public Sub DiscoverFinished
    ProgressDialogHide
    If Starter.Manager.foundDevices.Size = 0 Then
        ToastMessageShow("Устройства не найдены.", True)
    Else
        Dim l As List
        l.Initialize
        For Each nm As NameAndMac In Starter.Manager.foundDevices
            l.Add(nm.Name)
        Next
        InputListAsync(l, "Выберете устройство для подключения:", -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($"Попытка подключиться к: ${device.Name} (${device.Mac})"$, False)
        End If
    End If
End Sub

Public Sub AfterConnect (Success As Boolean)
    ProgressDialogHide
End Sub
B4X:
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    Public Manager As BluetoothManager
    Private a=0 As Int
End Sub

Sub Service_Create
'    Manager.Initialize
End Sub

Private Sub Service_Start (StartingIntent As Intent)
    If a=0 Then
        a=1
    Else
        Manager.Initialize
    End If
End Sub



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

Sub Service_Destroy
Why is this code not working?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
See the code in BluetoothManager.Initialize:
B4X:
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
It enables the Bluetooth adapter if it is not already enabled.
 
Upvote 0

red30

Well-Known Member
Licensed User
Longtime User
Thank you, I did it. That way :
Main:
B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: True
    #ApplicationLabel: Bluetooth Example
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region
#BridgeLogger: true
Sub Process_Globals
    Public Manager As BluetoothManager
    Private rp As RuntimePermissions
End Sub

Sub Globals
    Private btnSearchForDevices As Button
    Private btnAllowConnection As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
End Sub

Sub Activity_Resume
    'UpdateState
End Sub

Public Sub UpdateState
    btnSearchForDevices.Enabled = Starter.Manager.BluetoothState
    btnAllowConnection.Enabled = Starter.Manager.BluetoothState
End Sub

Sub Activity_Pause (UserClosed As Boolean)
   
End Sub

Sub BluetoothON
    Sleep(500)
    If Starter.Manager.BluetoothState Then
        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
    Else
        BluetoothON
    End If
End Sub

Sub btnSearchForDevices_Click
    If Starter.Manager.BluetoothState=False Then
        StartService(Starter)
    End If
'    Manager.Initialize
    BluetoothON
'    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

Public Sub 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 btnAllowConnection_Click
    Starter.Manager.ListenForConnections
End Sub
Starter:
B4X:
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    Public Manager As BluetoothManager
    Private temp=True As Boolean
End Sub

Sub Service_Create
'    Manager.Initialize
End Sub

Private Sub Service_Start (StartingIntent As Intent)
    If temp Then
        temp=False
    Else
        Manager.Initialize
    End If
End Sub



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

Sub Service_Destroy

End Sub

Still a question about How while searching the devices when at least one is found it will appear on the screen immediately in the list and the search goes on. How to do it?
 
Last edited:
Upvote 0
Top