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 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.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Iniciamos Tracker', '${Subs.fechaKMT(DateTime.now)}')"$) End Sub Sub flp_ConnectionSuccess If Starter.logger Then Log("Connected to location provider") 'FLP.GetLastKnownLocation End Sub Sub flp_ConnectionFailed(ConnectionResult1 As Int) If Starter.logger Then 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.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) Do While FLP.IsConnected = False Sleep(500) Log("sleeping") 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) ' 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.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)}')"$) Dim coords As String = Starter.UUC.Latitude & ","&Starter.UUC.Longitude & ","&Subs.formatoFecha(Starter.UUC.Time) Subs.mandaLocAServer(Starter.UUC, Starter.devModel) CallSubDelayed2(FirebaseMessaging,"mandamosLoc",coords) 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("timer enabled") If Starter.logger Then LogColor("FLP_LocationChanged", Colors.Red) ' ToastMessageShow("FLP_LocationChanged", False) Dim coords As String = Location1.Latitude&","&Location1.Longitude&","&Subs.formatoFecha(DateTime.Now) 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 CallSubDelayed2(FirebaseMessaging,"mandamosLoc", coords) Subs.mandaLocAServer(Location1, Starter.devModel) Dim coords As String = Location1.Latitude&","&Location1.Longitude&","&Subs.formatoFecha(Location1.Time) CallSubDelayed2(FirebaseMessaging,"mandamosLoc",coords) 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.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.gps_hist.ExecNonQuery($"insert into BITACORA (RUTA, TEXTO, FECHA) values ('${Starter.devModel}', 'Tracker - Service_Destroy', '${Subs.fechaKMT(DateTime.now)}')"$) End Sub