Sub Process_Globals
Private AlarmManager As JavaObject
End Sub
Sub Service_Create
Log("Starter Service Criado")
AlarmManager.InitializeStatic("android.app.AlarmManager")
End Sub
Sub Service_Start(StartingIntent As Intent)
Log("Starter Service Iniciado")
ProgramarExecucao()
StartService(Me) ' Garante que o serviço continue rodando
End Sub
Sub ProgramarExecucao()
Dim p As Phone
Dim tempoInicial As Long = DateTime.Now + 5 * DateTime.TicksPerSecond ' Início após 5 segundos
Dim intervalo As Long = 12 * DateTime.TicksPerHour ' A cada 12 horas
If p.SdkVersion >= 21 Then
ProgramarComJobScheduler(intervalo)
Else
ProgramarComAlarmManager(tempoInicial, intervalo)
End If
End Sub
' Para Android 5.0+ (JobScheduler)
Sub ProgramarComJobScheduler(intervalo As Long)
Try
Dim js As JavaObject
js.InitializeContext
Dim jobScheduler As JavaObject = js.RunMethod("getSystemService", Array("jobscheduler"))
Dim jobInfoBuilder As JavaObject
jobInfoBuilder.InitializeNewInstance("android.app.job.JobInfo.Builder", Array(1, Me))
jobInfoBuilder.RunMethod("setRequiredNetworkType", Array(1)) ' Exemplo: necessário Wi-Fi
jobInfoBuilder.RunMethod("setPeriodic", Array(intervalo))
jobScheduler.RunMethod("schedule", Array(jobInfoBuilder.RunMethod("build", Null)))
Log("JobScheduler configurado com sucesso!")
Catch
Log("Erro ao configurar JobScheduler: " & LastException.Message)
End Try
End Sub
' Para Android < 5.0 (AlarmManager)
Sub ProgramarComAlarmManager(tempoInicial As Long, intervalo As Long)
Dim pi As PendingIntent = CreatePendingIntent
AlarmManager.RunMethod("setRepeating", Array(AlarmManager.GetField("RTC_WAKEUP"), tempoInicial, intervalo, pi))
Log("AlarmManager configurado com sucesso!")
End Sub
Sub CreatePendingIntent As PendingIntent
Dim intent As Intent
intent.Initialize("", "")
Return PendingIntent.GetService(Application.Context, 0, intent, 0)
End Sub
Sub Service_Destroy
Log("Starter Service Destruído")
End Sub