Android Question BLE Android 9 - Scanning stops when screen turned off

Jmu5667

Well-Known Member
Licensed User
Hello

We are working with these devices, https://store.kontakt.io/next-generation/43-asset-tag-s18-3.html.

We have a service that runs and is scanning:

B4X:
#Region  Service Attributes
   #StartAtBoot: False
  
#End Region

Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.

   Private manager As BleManager2
   Private currentStateText As String = "UNKNOWN"
   Private currentState As Int
   Private scanning As Boolean
   Private bc As ByteConverter
      
   Private const TIME_TO_LIVE_SECONDS As Int = 30
  
   Private Timer1 As Timer
   Private rp As RuntimePermissions
   Private ManagerJO As JavaObject
   Private Adapter As JavaObject
   Private Scanner As JavaObject
   Private ScanCallback As JavaObject


End Sub

Sub Service_Create

   manager.Initialize("manager")
   ManagerJO = manager
   Adapter = ManagerJO.GetField("blueAdapter")
   Scanner = Adapter.RunMethod("getBluetoothLeScanner", Null)
   ScanCallback.InitializeNewInstance(Application.PackageName & ".svc_ble_sos_le$MyScanCallback", Null)
  
   Timer1.Initialize("hook",5000)

End Sub

Sub Service_Start (StartingIntent As Intent)
   Timer1.Enabled = True
  
   StartScan_le
  
  
End Sub

Sub Service_Destroy
  
   StopScanWithLeScanner
  
   Timer1.Enabled = False
   

End Sub

Sub hook_tick
  
   mod_functions.writelog("hook_tick() Still Running")
  
End Sub

Sub Manager_StateChanged (State As Int)
   Select State
       Case manager.STATE_POWERED_OFF
           currentStateText = "POWERED OFF"
       Case manager.STATE_POWERED_ON
           currentStateText = "POWERED ON"
       Case manager.STATE_UNSUPPORTED
           currentStateText = "UNSUPPORTED"
   End Select
   currentState = State

End Sub

Sub Manager_DeviceFound (Name As String, Id As String, AdvertisingData As Map, RSSI As Double)
  
   
  
End Sub

' // based on this answer: http://stackoverflow.com/questions/20416218/understanding-ibeacon-distancing
Private Sub CalculateDistance(tx As Int, rssi As Double) As Double
   If rssi = 0 Then Return -1
   Dim ratio As Double = rssi / tx
   If ratio < 1 Then
       Return Power(ratio, 10)
   Else
       Return 0.89976 * Power(ratio, 7.7095) + 0.111
   End If
End Sub

#region "LE Scanner"

Public Sub StartScan_le
   If manager.State <> manager.STATE_POWERED_ON Then
       Log("Not powered on.")
   Else If rp.Check(rp.PERMISSION_ACCESS_COARSE_LOCATION) = False Then
       Log("No location permission.")
   Else
       ScanWithLeScanner
   End If
End Sub


Private Sub Scan_Result (Result As Object)
  

   Dim ScanResult As JavaObject = Result
   Dim device As JavaObject = ScanResult.RunMethod("getDevice", Null)
   Dim address As String = device.RunMethod("getAddress", Null)
  
  
  
   ManagerJO.GetFieldJO("devices").RunMethod("put", Array(address, device))

   Dim name As String
   Dim o As Object = device.RunMethod("getName", Null)
   If o = Null Then name = "" Else name = o
   Dim ScanRecord As JavaObject = ScanResult.RunMethod("getScanRecord", Null)
   'Log(ScanRecord) 'you can extend the code to access the data.
   'https://developer.android.com/reference/android/bluetooth/le/ScanRecord
   Dim rssi As Double = ScanResult.RunMethod("getRssi", Null)
  
   log("svc_ble_sos_le() Scan_Result > name : " & name & ", rssi : " & rssi & ", " & address)
  
' // not called yet as screen off issue
'   Manager_DeviceFound(name, address, CreateMap(), rssi)
  
End Sub

Private Sub ScanWithLeScanner
   Dim ScanSettingsStatic As JavaObject
   ScanSettingsStatic.InitializeStatic("android.bluetooth.le.ScanSettings")
   Dim ScanSettingsBuilder As JavaObject
   ScanSettingsBuilder.InitializeNewInstance("android.bluetooth.le.ScanSettings.Builder", Null)
   'https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder
   ScanSettingsBuilder.RunMethod("setScanMode", Array(ScanSettingsStatic.GetField("SCAN_MODE_LOW_POWER")))
  
   Scanner.RunMethod("startScan", Array(Null, ScanSettingsBuilder.RunMethod("build", Null), ScanCallback))
End Sub

Private Sub StopScanWithLeScanner
   Scanner.RunMethod("stopScan", Array(ScanCallback))
End Sub


#End Region


#if Java
import android.bluetooth.le.*;
public static class MyScanCallback extends ScanCallback {
 public void onScanResult(int callbackType, ScanResult result) {
         processBA.raiseEvent(this, "scan_result", result);
    }

  

    /**
     * Callback when scan could not be started.
     *
     * @param errorCode Error code (one of SCAN_FAILED_*) for scan failure.
     */
    public void onScanFailed(int errorCode) {
       BA.Log("Error: " + errorCode);
    }
}
#End If

We have noticed that on Android 9 when the screen is turned off no more Scan_Result events are fired, and when the screen is turn back on the scan results resume.

We were using the standard Ble method that Erel provided, https://www.b4x.com/android/forum/threads/ble-2-bluetooth-low-energy.59937/#content

We switched to the above code example to see if it made a difference, the result was the same. It functioned fine up to Android 8.

Regards

John.
 

emexes

Expert
Licensed User
Bit too quick on the keyboard there... speaking of brain-fade, I forgot to mention that, when I used ScanFilter with the 0xffe0 service id, Scan2 found the iTag (and also other iTags that are scattered around this room as part of another little project...)
 
Upvote 0

emexes

Expert
Licensed User
the actual device that I want to use, the BLE example prog wont connect to it.

Ah, I thought the problem was that scanning stopped when the screen went off, and that had morphed into that screen-off scanning needed a service UUID to be specified.

Then again, it's kinda reasonable that you can't connect to a beacon, but that doesn't preclude it from advertising a service. Bit flirty of it, though, teasing us like that.

Send me a dump of the advertising data, because I might have had more of an idea of what I was doing bck there than I let on to ;-)
 
Upvote 0

Jmu5667

Well-Known Member
Licensed User
Ah, I thought the problem was that scanning stopped when the screen went off, and that had morphed into that screen-off scanning needed a service UUID to be specified.

Then again, it's kinda reasonable that you can't connect to a beacon, but that doesn't preclude it from advertising a service. Bit flirty of it, though, teasing us like that.

Send me a dump of the advertising data, because I might have had more of an idea of what I was doing than I let on to ;-)
will do
 
Upvote 0

Jmu5667

Well-Known Member
Licensed User
UUID = f7826da6-4fa2-4e98-8024-bc5b71e0893e

Advertising data Map
(MyMap) {1=[B@acd548c, -1=[B@977d7d5, 0=[B@f87fbea}

Key -1 : 4C000215F7826DA64FA24E988024BC5B71E0893EAE68A9FCB3
Key 0 : 0201061AFF4C000215F7826DA64FA24E988024BC5B71E0893EAE68A9FCB30000000000000000000000000000000000000000000000000000000000000000
Key 1 : 06
 
Last edited:
Upvote 0

emexes

Expert
Licensed User
UUID = f7826da6-4fa2-4e98-8024-bc5b71e0893f

Advertising data Map
(MyMap) {1=[B@acd548c, -1=[B@977d7d5, 0=[B@f87fbea}

Key -1 : 4C000215F7826DA64FA24E988024BC5B71E0893EAE68A9FCB3
Key 0 : 0201061AFF4C000215F7826DA64FA24E988024BC5B71E0893EAE68A9FCB30000000000000000000000000000000000000000000000000000000000000000
Key 1 : 06

Yikes, that was quick. I was about to post an alternate route to that cheese, being:

1/ Open the nRF Connect app

2/ Look through that list of advertising devices for the one we're scanning for:

upload_2019-3-5_1-19-56.png


3/ Expand that device:

upload_2019-3-5_1-20-48.png


4/ Click on "MORE":

upload_2019-3-5_1-21-34.png


5/ Click on "FLAGS & SERVICES":

upload_2019-3-5_1-22-32.png


and... Voila! (hopefully ;-)
 

Attachments

  • upload_2019-3-5_1-19-9.png
    upload_2019-3-5_1-19-9.png
    149.8 KB · Views: 107
Upvote 0

Jmu5667

Well-Known Member
Licensed User
Upvote 0

emexes

Expert
Licensed User
Looks like it does not support what I want to do ...

Yeah, that is looking a bit sad.

I'm still trying to decipher your advertising data. I was excited by the long field at the end, but it's a few digits short of the 32 needed for a full UUID.
 
Last edited:
Upvote 0

Jmu5667

Well-Known Member
Licensed User
Yeah, that is looking a bit sad.

I'm still trying to decipher your advertising data. I was excited by the long field at the end, but it's a few bytes short of the 32 needed for a full UID.
These guys have an SDK, https://developer.kontakt.io/mobile/android/sdk/ , I have download it, jar file and apparently they can scan filter for proximity UUIDs, I will have a look and see what I can find....
 
Upvote 0

emexes

Expert
Licensed User
I got a list of services from a different beacon, (same manufacturer, as I could not connect to the one we want to use)

Hey, did you try nRF Connect with both those beacons?

(as in, both the "different beacon" and "the one we want to use" beacon)
 
Upvote 0

Jmu5667

Well-Known Member
Licensed User
BTW, do know of any tags, that can :

1. Be filtered scanned (UUID's) in a background service
2. Have a button on it
2. Trigger some sort of New UUID, service data etc when pressed ?
 
Last edited:
Upvote 0

emexes

Expert
Licensed User
You can (usually) connect to devices with nRF Connect too, and then it'll give you more information (compared to what's in the advertisements)
 
Upvote 0
Top