Android Question How to read and save smartphone's sensor data from a service into a text file

Medel

Member
Licensed User
Hi, i've been trying to save the sensor data from a smartphone into a text file through a service every minute. The app runs without any error, I open the app, write the frequency to save the data, press a button to start the service and up to this point runs ok, but when I stop the app, and try to chek the store data...theres only zeros...

B4X:
#Region Module Attributes
    #FullScreen: True
    #IncludeTitle: True
    #ApplicationLabel: Servicio Infinito
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

Sub Process_Globals
    Dim periodo As Int
    periodo=200
End Sub

Sub Globals
    

    'INTERFACE: Etiquetas
    Private LAcelerometro     As Label
    Private LGiroscopio     As Label
    Private LLuz             As Label
    Private LOrientacion     As Label
    Private Button1         As Button
    Private ETFrecuencia     As EditText
    

End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then       
        Activity.LoadLayout("main")   
    End If
End Sub
 
Sub Activity_Resume
'    For i = 0 To SensorsMap.Size - 1
'        Dim ps As PhoneSensors
'        Dim sd As SensorData
'        ps = SensorsMap.GetKeyAt(i)
'        sd = SensorsMap.GetValueAt(i)
'        If ps.StartListening("Sensor") = False Then
'            Log(sd.Name & " No lo soporta.")
'        End If
'    Next
    
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub


Sub Button1_Click
    'Dim periodo As Int
    StartService(Starter)
    ToastMessageShow("adquiriendo",False)
    periodo = Ceil((1/ETFrecuencia.Text)*1000)
End Sub

Sub Button1_LongClick
    StopService(Starter)
    Starter.Timer1.Enabled=False
    ToastMessageShow("detenido",False)
End Sub

and the service CODE is:


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


Sub Process_Globals
    Dim SensorsMap As Map
    Type SensorData (Name As String, ThreeValues As Boolean)
    'TEMPORIZADORES: Periodo de almacenamiento
    Dim timer1 As Timer
    

    'Globals
    Dim SensorsLabels As Map
    'VARIABLES: del proceso
    Dim acelerometroX, acelerometroY, acelerometroZ    As Float
    Dim giroscopioX, giroscopioY, giroscopioZ        As Float
    Dim orientacionX, orientacionY, orientacionZ    As Float
    Dim hora, minuto, segundo, proximom, contador As Int
    Dim horaminuto1, horaminuto2 As String

    'VARIABLES: Listas

    Dim Listacelerometrox, Listacelerometroy, Listacelerometroz As List
    Dim Listgiroscopiox, Listgiroscopioy, Listgiroscopioz As List
    Dim Listorientacionx, Listorientaciony, Listorientacionz As List

    'INICIALIZACIÓN: Listas
    Listacelerometrox.initialize
    Listacelerometroy.initialize
    Listacelerometroz.initialize
    Listgiroscopiox.initialize
    Listgiroscopioy.initialize
    Listgiroscopioz.initialize
    Listorientacionx.initialize
    Listorientaciony.initialize
    Listorientacionz.initialize
    contador=0
    
End Sub

Sub Service_Create
    
        SensorsMap.Initialize
        'LLAMADO: SUBRUTINA: Agrega los sensores e inicializa
        Dim ps As PhoneSensors
        AddSensor(ps.TYPE_ACCELEROMETER, "Acelerometro", True)
        AddSensor(ps.TYPE_GYROSCOPE, "Giroscopio", True)
        AddSensor(ps.TYPE_LIGHT, "Luz", False)
        AddSensor(ps.TYPE_MAGNETIC_FIELD, "Brujula", True)
        AddSensor(ps.TYPE_ORIENTATION, "Orientacion", True)
        AddSensor(ps.TYPE_PRESSURE, "Presion", False)
        AddSensor(ps.TYPE_PROXIMITY, "Proximidad", False)
        AddSensor(ps.TYPE_TEMPERATURE, "Temperatura", False)
    
    'Mapa en donde se almacenará los datos del sensor
    For i = 0 To SensorsMap.Size - 1
        Dim ps As PhoneSensors
        ps = SensorsMap.GetKeyAt(i)
    Next
    
    Dim periodoservicio As Int
    periodoservicio=Main.periodo
    timer1.Initialize("timer1",periodoservicio)
    timer1.Enabled=True
    ToastMessageShow("Registro TXT activado",False)
    
    minuto = DateTime.GetMinute(DateTime.Now)
    proximom=minuto+1
    Listacelerometrox.Clear
    
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
    'Detiene la escucha de todos los eventos de los sensores
    For i = 0 To SensorsMap.Size - 1
        Dim ps As PhoneSensors
        ps = SensorsMap.GetKeyAt(i)
        ps.StopListening
    Next
    timer1.Enabled=False
    ToastMessageShow("Registro TXT DESactivado",False)
End Sub


Sub AddSensor(SensorType As Int, Name As String, ThreeValues As Boolean) As SensorData
    Dim sd As SensorData
    sd.Initialize
    sd.Name = Name
    sd.ThreeValues = ThreeValues
    Dim ps As PhoneSensors
    'Controla la frecuencia de adquisición máxima de los sensores
    ps.Initialize2(SensorType,0)
    SensorsMap.Put(ps, sd)
    Log(Name & " MaxValue = " & ps.MaxValue)
    
End Sub


Sub Sensor_SensorChanged (Values() As Float)
    Dim ps As PhoneSensors
    Dim sd As SensorData
    'obtiene los objetos de PhoneSensors
    ps = Sender
    'Obtiene el dato del sensor
    sd = SensorsMap.Get(ps)
    
    'Leyendo cada variable
    If sd.Name=="Acelerometro" Then
        'LAcelerometro.Text=sd.Name & " X=" & NumberFormat(Values(0), 0, 3) & ", Y=" & NumberFormat(Values(1), 0, 3) & ", Z=" & NumberFormat(Values(2), 0, 3)
        acelerometroX=NumberFormat(Values(0), 0, 3)
        acelerometroY=NumberFormat(Values(1), 0, 3)
        acelerometroZ=NumberFormat(Values(2), 0, 3)
    End If
    If sd.Name=="Giroscopio" Then
        'LGiroscopio.Text=sd.Name & " X=" & NumberFormat(Values(0), 0, 3) & ", Y=" & NumberFormat(Values(1), 0, 3) & ", Z=" & NumberFormat(Values(2), 0, 3)
        giroscopioX=NumberFormat(Values(0), 0, 3)
        giroscopioY=NumberFormat(Values(1), 0, 3)
        giroscopioZ=NumberFormat(Values(2), 0, 3)
    End If

    If sd.Name=="Orientacion" Then
        'LOrientacion.Text=sd.Name & " X=" & NumberFormat(Values(0), 0, 3) & ", Y=" & NumberFormat(Values(1), 0, 3) & ", Z=" & NumberFormat(Values(2), 0, 3)
        orientacionX=NumberFormat(Values(0), 0, 3)
        orientacionY=NumberFormat(Values(1), 0, 3)
        orientacionZ=NumberFormat(Values(2), 0, 3)
    End If
        
End Sub

Sub timer1_tick
    'Espera la reconexión
    timer1.Enabled=False
    'LAcelerometro.Text="Acelerometro=" & " X=" & acelerometroX & ", Y=" & acelerometroY & ", Z=" & acelerometroZ
    'LGiroscopio.Text="Giroscopio=" & " X=" & giroscopioX & ", Y=" & giroscopioY & ", Z=" & giroscopioZ
    'LOrientacion.Text="Orientacion=" & " X=" & orientacionX & ", Y=" & orientacionY & ", Z=" & orientacionZ
    
    contador=contador+1
    
    'Agregar objetos a la lista
    Listacelerometrox.Add(acelerometroX)
    Listacelerometroy.Add(acelerometroY)
    Listacelerometroz.Add(acelerometroZ)
    
    Listgiroscopiox.Add(giroscopioX)
    Listgiroscopioy.Add(giroscopioY)
    Listgiroscopioz.Add(giroscopioZ)
    
    Listorientacionx.Add(orientacionX)
    Listorientaciony.Add(orientacionY)
    Listorientacionz.Add(orientacionZ)

    'Agrega renglon
    'Lee la hora y minutos
    hora = DateTime.GetHour(DateTime.Now)
    minuto = DateTime.GetMinute(DateTime.Now)
    segundo= DateTime.GetSecond(DateTime.Now)

    horaminuto1= hora & ":" & minuto& ":"  & segundo
    
    If(minuto==proximom) Then
        contador=0
        proximom=minuto+1
        ToastMessageShow("paso un minuto", False)
        'Cabeza agregado
        Listacelerometrox.Add(Chr(13)&horaminuto1& TAB)
        Listacelerometroy.Add(Chr(13)&horaminuto1& TAB)
        Listacelerometroz.Add(Chr(13)&horaminuto1& TAB)
        
        Listgiroscopiox.Add(Chr(13)&horaminuto1& TAB)
        Listgiroscopioy.Add(Chr(13)&horaminuto1& TAB)
        Listgiroscopioz.Add(Chr(13)&horaminuto1& TAB)
        
        Listorientacionx.Add(Chr(13)&horaminuto1& TAB)
        Listorientaciony.Add(Chr(13)&horaminuto1& TAB)
        Listorientacionz.Add(Chr(13)&horaminuto1& TAB)
        
        'Se almacena la información en texto
        File.Writestring(File.DirRootExternal, "acelerometrox.txt", Listacelerometrox)
        File.Writestring(File.DirRootExternal, "acelerometroy.txt", Listacelerometroy)
        File.Writestring(File.DirRootExternal, "acelerometroz.txt", Listacelerometroz)
        
        File.Writestring(File.DirRootExternal, "giroscopiox.txt", Listgiroscopiox)
        File.Writestring(File.DirRootExternal, "giroscopioy.txt", Listgiroscopioy)
        File.Writestring(File.DirRootExternal, "giroscopioz.txt", Listgiroscopioz)
        
        File.Writestring(File.DirRootExternal, "orientacionx.txt", Listorientacionx)
        File.Writestring(File.DirRootExternal, "orientaciony.txt", Listorientaciony)
        File.Writestring(File.DirRootExternal, "orientacionz.txt", Listorientacionz)
        
        
    End If

    timer1.Enabled=True

End Sub


Sub Service_TaskRemoved
    'This event will be raised when the user removes the app from the recent apps list.
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
I don't know why keeps saving zeros the data...I've tried to do it without the service (only one activity an one layout)and there's no problem, any ideas?
 

MarkusR

Well-Known Member
Licensed User
maybe u need here .WriteList
B4X:
File.Writestring(File.DirRootExternal, "orientacionx.txt", Listorientacionx)
use debug mode & break points to verify values.

try also using a Type for structs
 

Medel

Member
Licensed User
maybe u need here .WriteList
B4X:
File.Writestring(File.DirRootExternal, "orientacionx.txt", Listorientacionx)
use debug mode & break points to verify values.

try also using a Type for structs
Hi MarkusR, I've tried to use Logs and debug to check the problem. The process globals runs ok, then the add sensor part, service create, also the service start it's ok...but somehow the Sensor_changed part never gets activate, that's why keeps writting zeros.

I'm also using Labview to draw the data from the sensors, and it has to be a "File.Writestring..." so the labview software could read it without a problem.

The goal is to use the smartphone sensors to acquire its data and draw a 24 hours graph divided into minutes to choose from. All of that it's done, except the reading part from the sensors within a service.
 

MarkusR

Well-Known Member
Licensed User
you forgot
B4X:
ps.StartListening("Sensor")
?

above example is comment out
 
Top