Sub Process_Globals
Private SensorManager As JavaObject
Private Listeners As Map
Private StaticSensor As JavaObject
Private SensorToString As Map
Private hash As Int
End Sub
Sub Service_Create
Dim ctxt As JavaObject
ctxt.InitializeContext
SensorManager = ctxt.RunMethodJO("getSystemService", Array("sensor"))
StaticSensor.InitializeStatic("android.hardware.Sensor")
Listeners.Initialize
SensorToString.Initialize
Log(StartListening("LINEAR_ACCELERATION", 3, 500))
Log(StartListening("LIGHT", 3, 500))
End Sub
'Sampling period: 3 - DELAY_NORMAL, DELAY_UI - 2, 1 - DELAY_GAME, 0 - DELAY_FASTEST
Public Sub StartListening (Sensor As String, SamplingPeriod As Int , MaxReportLatencyUs As Int) As Boolean
StopListening (Sensor)
hash = hash + 1
Dim Listener As Object = SensorManager.CreateEventFromUI("android.hardware.SensorEventListener", "Listener", hash)
Listeners.Put(Sensor, Listener)
Dim s As JavaObject = SensorManager.RunMethod("getDefaultSensor", Array(StaticSensor.GetField("TYPE_" & Sensor)))
If s = Null Then Return False
SensorToString.Put(s, Sensor)
Dim p As Phone
If p.SdkVersion >= 19 Then
Return SensorManager.RunMethod("registerListener", Array(Listener, s, SamplingPeriod, MaxReportLatencyUs))
Else
Return SensorManager.RunMethod("registerListener", Array(Listener, s, SamplingPeriod))
End If
End Sub
Private Sub Listener_Event (MethodName As String, Args() As Object) As Object
If MethodName = "onSensorChanged" Then
Dim event As JavaObject = Args(0)
Dim sensor As String = SensorToString.Get(event.GetField("sensor"))
Dim values() As Float = event.GetField("values")
'log it with:
Dim l As List = values
Log($"${sensor}: ${l}"$)
End If
Return Null
End Sub
Public Sub StopListening (Sensor As String)
If Listeners.ContainsKey(Sensor) Then
Dim listener As Object = Listeners.Get(Sensor)
SensorManager.RunMethod("unregisterListener", Array(listener))
Listeners.Remove(Sensor)
End If
End Sub