Android Question (Solved) Bluetooth StartDiscovery return false if in background

Paolo Pini

Member
Licensed User
Longtime User
Hi all,

I created a Service that list all the bluetooth device in area.
The app works well until is in foreground, if I open other app or minimize my app the StartDiscovery return always false.
The service appear to still active because I can see the toast messages and the logs() that appear if the app is minimize also.

Its a limit of Android release or something else?

Many thanks in advance

Paolo

B4X:
' **********************************
Sub StartSearchForDevices
    If FlgDebug Then Log("StartSearchForDevices")

    ' Start timeout search timer
    StartTmrTimeout
   
    Log(admin.StartDiscovery)
End Sub

Manifest:
AddManifestText(
<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="33"/>

<supports-screens android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
CreateResourceFromFile(Macro, Themes.LightTheme)
'End of default text.

AddPermission(android.permission.BLUETOOTH_SCAN)
AddPermission(android.permission.BLUETOOTH_CONNECT)

AddApplicationText(
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />

<meta-data
  android:name="com.google.android.geo.API_KEY"
  android:value="AIzaSyAFj4o-asLRNr5YnBktyJqZiCP0I5nNVXM"/>
)

SetServiceAttribute(Tracker, android:foregroundServiceType, "location")
 

Paolo Pini

Member
Licensed User
Longtime User
Check the unfiltered logs. Might be more information there.
Your app requests the location permission, right?
I tried looking at the unfiltered log but I can't see anything obvious even though I'm not very knowledgeable about this.
this my manifest:

Manifest:
'This code will be applied to the manifest file during compilation.
'You do not need to modify it in most cases.
'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136
' con 30 funziona

AddManifestText(
<uses-sdk android:minSdkVersion="5" android:targetSdkVersion="33"/>

<supports-screens android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:anyDensity="true"/>)
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
CreateResourceFromFile(Macro, Themes.LightTheme)
'End of default text.

'AddPermission(android.permission.BLUETOOTH_SCAN)
'AddPermission(android.permission.BLUETOOTH_CONNECT)

AddPermission(android.permission.BLUETOOTH_SCAN)
AddPermission(android.permission.BLUETOOTH)
AddPermission(android.permission.BLUETOOTH_ADMIN)
AddPermission(android.permission.BLUETOOTH_CONNECT)
AddPermission(android.permission.ACCESS_FINE_LOCATION)
AddPermission(android.permission.ACCESS_COARSE_LOCATION)

AddApplicationText(
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />

<meta-data
  android:name="com.google.android.geo.API_KEY"
  android:value="AIzaSyAFj4o-asLRNr5YnBktyJqZiCP0I5nxxxx"/>
)

SetServiceAttribute(Tracker, android:foregroundServiceType, "bluetooth")
SetServiceAttribute(Tracker, android:foregroundServiceType, "location")

Sub Activity_Resume:
Sub Activity_Resume
    Dim Permissions As List
    Dim rp As RuntimePermissions

    Wait For (CheckAndRequestNotificationPermission) Complete (HasPermission As Boolean)
 
    If HasPermission = False Then
        Log("no permission")
        ToastMessageShow("no permission", True)
        Return
    End If
 
    Permissions = Array("android.permission.BLUETOOTH_SCAN", "android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN","android.permission.BLUETOOTH_CONNECT", rp.PERMISSION_ACCESS_FINE_LOCATION,rp.PERMISSION_ACCESS_COARSE_LOCATION)
     
    For Each per As String In Permissions
        rp.CheckAndRequest(per)
     
        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
 
        If Result Then
            StartService(Tracker)
        Else
            ToastMessageShow("No permission...", True)
        End If
    Next
End Sub

the programm acquires GPS coordinates and sends them to a Bluetooth device, the GPS seems to keep working in the background while the Bluetooth does not.
I noticed that 'admin.enable' remains true and if I periodically call up 'admin.StartDiscovery' the devices are detected.

To do some tests, I modified the your 'MyLocation' example by adding bluetooth management:

B4X:
' **********************************
Sub GPS_LocationChanged (Location1 As Location)
    Log("GPS_LocationChanged")
    If DateTime.Now > LastUpdateTime + 5 * DateTime.TicksPerSecond Then
        Dim n As Notification = CreateNotification($"$2.5{Location1.Latitude} / $2.5{Location1.Longitude}"$)
        n.Notify(nid)
        LastUpdateTime = DateTime.Now
    End If
End Sub

' **********************************
Sub CreateNotification (Body As String) As Notification
    Log("CreateNotification")
    Dim notification As Notification
    notification.Initialize2(notification.IMPORTANCE_LOW)
    notification.Icon = "icon"
    notification.SetInfo("Tracking location:" & DateTime.Time(DateTime.Now) & "-" & foundDevices.Size, Body, Main)
    Return notification
End Sub

' **********************************
Private Sub Admin_DeviceFound (Name As String, MacAddress As String)
    Log("Admin_DeviceFound")

    Dim nm As NameAndMac
    Dim nmEx As NameAndMac
    Dim FlgFound As Boolean=False
 
    nm.Name = Name
    nm.Mac = MacAddress
 
    Log(Name & " - " & MacAddress)
 
    If foundDevices.Size>0 Then
        For i=0 To foundDevices.Size-1
            nmEx=foundDevices.Get(i)
         
            If nmEx.Mac=nm.Mac Then
                FlgFound =True    'already exist
                Exit
            End If
        Next
    End If
     
    'add new device found
    If FlgFound =False Then
        foundDevices.Add(nm)
    End If
End Sub

Furthermore, in my application, when I put the application in the background I get these lines in the log:

B4X:
** Activity (main) Pause, UserClosed = false **
PerfMonitor: Slow Operation: Activity it.myname.searchcarbt/.main onPause took 106ms
onWindowFocusChanged hasWindowFocus false
set_timerslack_ns write failed: Operation not permitted
PerfMonitor longMsg : seq=104735 plan=12:03:59.840 late=0ms wall=1089ms running=0ms h=android.os.Handler c=anywheresoftware.b4a.objects.Timer$TickTack procState=-1
PerfMonitor looperActivity : package=it.myname.searchcarbt/.main time=10ms latency=917ms running=0ms  procState=-1  historyMsgCount=5 (msgIndex=1 wall=1089ms seq=104735 h=android.os.Handler c=anywheresoftware.b4a.objects.Timer$TickTack)
22965-ScoutStateMachinecreated
** Activity (main) Resume **
onWindowFocusChanged hasWindowFocus true
set_timerslack_ns write failed: Operation not permitted
** Service (tracker) Start **


and even here the GPS periodically returns coordinates while the Bluetooth returns 0 devices found unless periodically calling up 'admin.StartDiscovery' then for a few moments the search is successful.

Translated with DeepL.com (free version)
 
Last edited:
Upvote 0

Paolo Pini

Member
Licensed User
Longtime User
Basically, I would like to know how to keep the Bluetooth connection active even when the application is paused.

could this be a problem? (set_timerslack_ns write failed: Operation not permitted)

Many thanks.

Paolo
 
Upvote 0

Paolo Pini

Member
Licensed User
Longtime User
ok, i think i've solved the foreground handling, the app continues to handle bluetooth and gps even when paused, now i have to find out how to stop it because even if i close it it keeps running :)
 
Upvote 0
Top