B4A=true Group=Default Group ModulesStructureVersion=1 Type=Service Version=9.85 @EndOfDesignText@ #Region Service Attributes #StartAtBoot: False #ExcludeFromLibrary: True #End Region Sub Process_Globals 'These global variables will be declared once when the application starts. 'These variables can be accessed from all modules. Public rp As RuntimePermissions Dim s As C_Subs Dim reqManager As DBRequestManager Dim db, errorLog As SQL Dim ruta As String Public BluetoothState As Boolean Dim btAdmin As BluetoothAdmin Dim intentosImpresora As Int = 0 Dim revisandoImpresora As Boolean = False Public FLP As FusedLocationProvider Dim GPS As GPS 'Para ENVIA_ULTIMA_GPS Dim Timer1 As Timer Dim Interval As Int = 300 Dim server As String Dim pe As PhoneEvents Dim ph As Phone Dim marcaCel As String = ph.manufacturer Dim rutaTipo As String = "TRADICIONAL" 'Para los Logs Dim logs As StringBuilder Private logcat As LogCat Dim rutaV As String = "" Dim montoActual, clientesTotal, clientesVenta, clientesVisitados, almacen, rutaPreventa, CANTIDADPROD As String 'ignore Dim lat_gps, lon_gps As String Dim ubicacionActual As Location Dim FECHA_HOY As String Dim usuario As String Dim tipov As String Dim MAC_IMPRESORA As String Dim batt As Int Dim ultimaActualizacionGPS As String = 235959 ' Dim fechaRuta As String 'ignore Dim tiempos As Map Dim Logger As Boolean = False Dim ultimaActividad As String = "" Dim boleta As String = 0 Dim sesion As Map ' dim cp_running as Boolean = false End Sub Sub Service_Create 'This is the program entry point. 'This is a good place to load resources that are not specific to a single activity. s.Initialize(Me, "Subs") 'Inicializamos la clase Subs If Logger Then LogColor("'/////////////////////////////////////////////////////////////////////////////////////////////", Colors.Green) If Logger Then LogColor("'///////////////////////////////////// Iniciamos Starter /////////////////////////////////", Colors.Green) If Logger Then LogColor("'/////////////////////////////////////////////////////////////////////////////////////////////", Colors.Green) Timer1.Initialize("Timer1", Interval * 1000) Timer1.Enabled = True GPS.Initialize("GPS") ubicacionActual.Initialize pe.Initialize("pe") 'Para obtener la bateria db = s.dbInit 'Inicializamos BD. server = "http://keymon.lat:1782" Private c As Cursor = db.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'SERVER'"$) If c.RowCount > 0 Then c.Position = 0 server = c.GetString("CAT_VA_VALOR") End If c.Close reqManager.Initialize(Me, server) 'Inicializamos reqManager. If Logger Then Log($"Starter reqManager server: ${server}"$) 'Para los Logs #if RELEASE logcat.LogCatStart(Array As String("-v","raw","*:F","B4A:v"), "logcat") #end if logs.Initialize sesion.Initialize End Sub Sub Service_Start (StartingIntent As Intent) Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases. Subs.revisaBD #if DEBUG Logger = True #else Logger = False #End If End Sub Sub Subs_dbOk(success As Boolean) LogColor($"Conexión con base de datos: ${success}"$, Colors.red) End Sub Sub Service_TaskRemoved 'This event will be raised when the user removes the app from the recent apps list. Timer1.Enabled=False End Sub 'Return true to allow the OS default exceptions handler to handle the uncaught exception. 'Para los Logs Sub Application_Error (Error As Exception, StackTrace As String) As Boolean 'wait for 500ms to allow the logs to be updated. Dim jo As JavaObject Dim l As Long = 500: jo.InitializeStatic("java.lang.Thread").RunMethod("sleep", Array(l)) 'Sleep 500ms logcat.LogCatStop logs.Initialize logs.Append("Ver " & Application.VersionName & CRLF) logs.Append("R:" & rutaV & CRLF) logs.Append(StackTrace) Subs.revisaBD Subs.errorLog.ExecNonQuery2("INSERT INTO errores(fecha, error) VALUES (?,?)", Array As Object (Subs.fechaKMT(DateTime.now), logs)) StartActivity(errorManager) Return True End Sub Sub Service_Destroy ' Timer1.Enabled=False If Logger Then LogColor("starter destroyed", Colors.red) End Sub Sub pe_BatteryChanged (Level As Int, Scale As Int, Plugged As Boolean, Intent As Intent) batt=Level End Sub Private Sub Timer1_Tick ' ToastMessageShow("Timer",False) If Logger Then Log("Siguiente actualizacion " & DateTime.Time(DateTime.Now + Interval * 1000)) ENVIA_ULTIMA_GPS 'Comentado para que no estorbe hasta que no esten los queries correctos en el config.properties End Sub Sub reinicializaReqManager reqManager.Initialize(Me, server) If Logger Then Log(server) End Sub Sub ENVIA_ULTIMA_GPS If Logger Then Log("Iniciamos ENVIA_ULTIMA_GPS") If Not(db.IsInitialized) Then db.Initialize(ruta,"kmt.db", True) DateTime.TimeFormat = "HHmmss" ultimaActualizacionGPS = DateTime.Time(DateTime.Now) Private s1 As Cursor = db.ExecQuery2("select CAT_VA_VALOR as semana from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SEMANA")) 'Traemos la semana. If s1.RowCount> 0 Then s1.Position=0 Private laSemana As String = s1.GetString("semana") Else Private laSemana As String = "" End If Private cpv As Cursor = db.ExecQuery2("select count(*) as CUANTOS from kmt_info where CAT_CL_DIAS_VISITA = (SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?) and cat_cl_codigo <> 0 AND CAT_CL_TIPO_RUTA IN (?,?) ORDER BY CAT_CL_NUM_SERIEFISICO", Array As String("DIA_VISITA", laSemana, "SEMANAL"))'Traemos los clientes a visitar hoy. cpv.Position=0 Private clientesVisitaHoy As String = cpv.GetString("CUANTOS") If lat_gps = 0 Or lat_gps = Null Then 'Si latitud es CERO o NULL traemos las ultimas coordenadas de la base de datos. Private coords As List = Subs.traeCoordsDeBD lat_gps = coords.Get(0) lon_gps = coords.Get(1) End If s1.Close cpv.Close Private rtec, ping, salty As String ' Log(Application.VersionName) Subs.dameClientesFueraDeFrecuencia Private h As Cursor For Each i As String In Array As String ("RTEC", "PING", "SALTY SNACKS") h=db.ExecQuery2("Select sum(PE_COSTO_TOT) As MONTO_DIA from pedido where PE_CLIENTE <> 0 and pe_proid in (Select CAT_GP_ID from cat_gunaprod2 where CAT_GP_TIPO = ? )", Array As String(i)) Private x As String = 0 If h.RowCount > 0 Then h.Position = 0 x = $"$1.3{h.GetString("MONTO_DIA")}"$ End If x = $"$1.3{x}"$ If x="NaN" Then X = "0" If i = "RTEC" Then rtec = x If i = "PING" Then ping = x If i = "SALTY SNACKS" Then salty = x Next h.Close Dim cmd As DBCommand cmd.Initialize cmd.Name = "UPDATE_KELL_ACTUAL3_GPS" cmd.Parameters = Array As Object(montoActual, clientesVisitaHoy, clientesVenta, clientesVisitados, lat_gps, lon_gps, batt, 0, 0, 0, Application.VersionName, rtec, ping, salty, Subs.dameClientesFueraDeFrecuencia, almacen, rutaPreventa) ' If Logger Then LogColor(montoActual&","&clientesVisitaHoy&","&clientesVenta&","&clientesVisitados&","&lat_gps&","&lon_gps&","&batt&","&0&","&0&","&0&","&Application.VersionName&","&rtec&","&ping&","&salty&","& Subs.dameClientesFueraDeFrecuencia&","&almacen&","&rutaPreventa, Colors.Magenta) reqManager.ExecuteCommand(cmd,"updateKell_UTR") ' If Logger Then Log(reqManager) ' If Logger Then Log("++ ++ ++ Envia_Ultima GPS - Inst_visitas - server: "& server) db.ExecNonQuery2("Update cat_variables set CAT_VA_VALOR = ? WHERE CAT_VA_DESCRIPCION = ?" , Array As String(DateTime.Time(DateTime.Now),"HoraIngreso")) 'Reiniciamos el timer para cuando llamamos el Sub desde otra actividad Timer1.Enabled = False Timer1.Interval = Interval * 1000 Timer1.Enabled = True End Sub Sub JobDone(Job As HttpJob) Log("JOBDONE STARTER") If Job.Success = False Then ' ToastMessageShow("Error: " & Job.ErrorMessage, True) Else If Logger Then LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green) 'Mod por CHV - 211110 If Job.JobName = "DBRequest" Then Dim result As DBResult = reqManager.HandleJob(Job) If result.Tag = "updateKell_UTR" Then 'query tag For Each records() As Object In result.Rows For Each k As String In result.Columns.Keys ' If Logger Then Log("Ubicacion en tiempo real: " & k & ": " & records(result.Columns.Get(k))) Next Next End If End If End If Job.Release End Sub 'Para los Logs Private Sub logcat_LogCatData (Buffer() As Byte, Length As Int) logs.Append(BytesToString(Buffer, 0, Length, "utf8")) If logs.Length > 4000 Then logs.Remove(0, logs.Length - 2000) 'Obtenemos log de 2000 ~ 4000 chars End If End Sub 'Revisa que la conexion a la base de datos este bien. Sub revisaBD 'ignore If Logger Then Log("revisaBD") If Not(File.Exists(ruta, "kmt.db")) Then File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db") If Not(db.IsInitialized) Then db.Initialize(ruta, "kmt.db", True) End Sub