Files
FLP_2.0/Tracker.bas

199 lines
7.1 KiB
QBasic

B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Service
Version=10.5
@EndOfDesignText@
#Region Service Attributes
#StartAtBoot: True
#End Region
'******************************************************************************
'No olvidar agregar esta linea al editor de manifiesto:
' SetServiceAttribute(Tracker, android:foregroundServiceType, "location")
'
'En Starter agregar estas lineas en Process_Globals
' Public rp As RuntimePermissions
' Public FLP As FusedLocationProvider
' Private flpStarted As Boolean
'
'En Main agregar estas lineas a Activity_Resume
' Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
' Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
' If Result Then
' StartService(Tracker)
' Log("Start Tracker")
' Else
' ToastMessageShow("No permission", True)
' End If
'
'Se necesitan las librerias FusedLocationProvider, GPS, Phone y RunTimePermissions
'
'Y en Main agregar estas dos lineas:
'#AdditionalJar: com.android.support:support-v4
'#AdditionalJar: com.google.android.gms:play-services-location
Sub Process_Globals
Private nid As Int = 1
Private Tracking As Boolean
Private lock As PhoneWakeState
'Para FusedLocationProvider (2 lineas)
Public flp As FusedLocationProvider
Private flpStarted As Boolean
Dim minAccuracy As Int = 50
Dim killerCalled As Int = 0
End Sub
Sub Service_Create
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves
'Para FusedLocationProvider (2 lineas)
flp.Initialize("flp")
flp.Connect
lock.PartialLock
StartFLP
If Starter.logger Then Log("FLP initialized")
Subs.bitacora($"Iniciamos Tracker"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Iniciamos Tracker', '${Subs.fechaKMT(DateTime.now)}')"$)
End Sub
Sub flpReConnect
Try
If killerCalled = 0 Then
killerCalled = 1
Subs.bitacora("Llamamos RESTART-TRACKER")
CallSubDelayed(Starter, "restartTracker")
Else
Subs.bitacora("Llamamos EXIT-APP")
ExitApplication
End If
Catch
Log(LastException)
End Try
End Sub
Sub flp_ConnectionSuccess
Log("FLP - Connected to location provider")
'FLP.GetLastKnownLocation
End Sub
Sub flp_ConnectionFailed(ConnectionResult1 As Int)
Log("Failed to connect to location provider")
End Sub
Sub Service_Start (StartingIntent As Intent)
'Para FusedLocationProvider (1 linea)
Service.StopAutomaticForeground
Service.StartForeground(nid, Subs.CreateNotification("..."))
Track
StartServiceAt(Me, DateTime.Now + 10 * DateTime.TicksPerMinute, True)
Subs.bitacora($"Tracker - Service_Start"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Tracker - Service_Start', '${Subs.fechaKMT(DateTime.now)}')"$)
End Sub
Public Sub Track
'Log("Track")
If Tracking Then Return 'Si ya estamos "rastreando" no hacemos nada (return)
If Starter.rp.Check(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION) = False Then
Log("No permission")
Return
End If
StartFLP 'Iniciamos FusedLocationProvider
Tracking = True
End Sub
Public Sub StartFLP
' Log("StartFLP - flpStarted="&flpStarted)
Private cont As Int = 0
Do While flp.IsConnected = False
Sleep(500)
Log($"FLP Sleeping - ${cont}"$)
Subs.bitacora($"Sleeping - ${cont}"$)
cont = cont + 1
If cont > 70 Then
cont = 0
Log("Reiniciamos FLP")
flpReConnect
End If
Loop
' If flpStarted = False Then
' Log("RequestLocationUpdates")
' Starter.FLPStatus = "Searching" : LogColor("FLP Searching", Colors.blue)
flp.RequestLocationUpdates(CreateLocationRequest) 'Buscamos ubicacion
flpStarted = True
' End If
End Sub
Private Sub CreateLocationRequest As LocationRequest
' Log("CreateLocationRequest")
' Starter.FLPStatus = "Searching" : LogColor("FLP Searching", Colors.blue)
Dim lr As LocationRequest
lr.Initialize
lr.SetInterval(30000) 'Intervalo deseado para actualizaciones de ubicacion en milisegundos
lr.SetFastestInterval(lr.GetInterval / 2) 'Intervalo minimo para actualizaciones de ubicacion
lr.SetSmallestDisplacement(30) 'Solo registra cambio de ubicacion si es mayor a XX mts
lr.SetPriority(lr.Priority.PRIORITY_HIGH_ACCURACY)
Return lr
End Sub
Sub dameUltimaUbicacionConocida(lastLocation As Location) 'ignore
If Starter.logger Then LogColor("dameUltimaUbicacionConocida", Colors.Magenta)
' Subs.gps_hist.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT)")
If Starter.logger Then Log("This accuracy: " & Starter.UUC.Accuracy)
Subs.bitacora($"Enviamos UUC - Acc: ${Starter.UUC.Accuracy}, Time:${Starter.UUC.Time}"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Enviamos UUC - Acc: ${Starter.UUC.Accuracy}, Time:${Starter.UUC.Time}', '${Subs.fechaKMT(DateTime.now)}')"$)
Subs.mandaLocAServer(Starter.UUC, Starter.devModel)
FirebaseMessaging.locRequest = "Activa"
CallSubDelayed2(FirebaseMessaging,"mandamosLoc", Starter.UUC)
If Starter.logger Then Log("Mandamos GetLastKnownLocation : "&DateTime.Time(flp.GetLastKnownLocation.Time))
If Starter.logger Then Log($"UUC: ${Starter.UUC.Latitude},${Starter.UUC.Longitude}"$)
End Sub
Public Sub StopFLP
'Log("StopFLP")
If flpStarted Then
flp.RemoveLocationUpdates 'Eliminamos todas las solicitudes de ubicacion
flpStarted = False
End If
End Sub
Sub flp_LocationChanged (Location1 As Location)
' Starter.FLPStatus = "Location changed" : LogColor("Location changed", Colors.blue)
Dim el_texto As String = ""
Starter.UUC = Location1
If Not(Starter.Timer1.Enabled) Then
Starter.Timer1.Enabled = True
Log("FLP - Timer Enabled")
End If
If Starter.logger Then LogColor("FLP_LocationChanged", Colors.Red)
' ToastMessageShow("FLP_LocationChanged", False)
Main.laUbicacion = Location1
' ToastMessageShow(coords, False)
' Log("Mandamos Ubicacion")
If Starter.logger Then Log(FirebaseMessaging.locRequest)
If Starter.logger Then Log(Location1)
If Starter.logger Then Log(Location1.Accuracy&" - "&Location1.AccuracyValid)
' solo mandamos la ubicacion si la precision es dentro de XX mts
el_texto = $"LocChange - Coords NO enviadas (Acc:${Location1.Accuracy})."$
If Location1.Accuracy < minAccuracy Then
Subs.mandaLocAServer(Location1, Starter.devModel)
FirebaseMessaging.locRequest = "Activa"
CallSubDelayed2(FirebaseMessaging,"mandamosLoc", Location1)
el_texto = $"LocChange - Coords enviadas (Acc:${Location1.Accuracy})."$
End If
If Starter.logger Then Log("Loc changed : "&Location1.Latitude&","&Location1.Longitude&"|"&Starter.devModel&"|")
Subs.gps_hist.ExecNonQuery("CREATE TABLE IF NOT EXISTS BITACORA(RUTA TEXT, TEXTO TEXT, FECHA TEXT)")
Subs.bitacora($"${el_texto}"$)
ToastMessageShow(el_texto, False)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', '${el_texto}', '${Subs.fechaKMT(DateTime.now)}')"$)
CallSubDelayed(Main, "ponCoords")
End Sub
Sub Service_Destroy
If Tracking Then
StopFLP
End If
Tracking = False
lock.ReleasePartialLock
Subs.bitacora($"Tracker - Service_Destroy"$)
' Subs.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Tracker - Service_Destroy', '${Subs.fechaKMT(DateTime.now)}')"$)
End Sub