Android Question Help with Running an App Twice a Day

dank

Member
Licensed User
Longtime User
I have an app that I want to run twice a day. It collects data from the web, processes it, and stores it in a database. It sends out a notification I've been trying out services and receivers, but I can't get the app to always run properly. I've tried out most of the example code I could find (alarms, etc.), but, after working on it for a week, I finally decided to ask for help.

Can someone provide some code that will work whatever the app's (and phone's) situation? Thanks!
 

Flavio SOuza

Member
Licensed User
Longtime User
You can use Starter Service and receivers to ensure it runs reliably at scheduled times. To do this, use JobScheduler or an AlarmManager, which are designed for scheduled tasks on Android.


Make sure you have the Starter service configured in your project. It is used to launch the app and maintain background tasks.
servi:
Sub Process_Globals
    Private ScheduledJob As Timer
End Sub

Sub Service_Create
    ' Inicializa o timer para evitar problemas de inicialização
    ScheduledJob.Initialize("ScheduledJob", 1000) ' Timer inicial de 1 segundo
End Sub

Sub Service_Start (StartingIntent As Intent)
    StartServiceAtExact("", DateTime.Now + 5000, True) ' Garante a execução do serviço
    ProgramJobScheduler() ' Programa as execuções futuras
End Sub

Sub ProgramJobScheduler()
    Dim p As Phone
    If p.SdkVersion >= 21 Then
        Dim js As JavaObject
        js.InitializeStatic("android.app.job.JobScheduler")
        Dim job As JavaObject
        job.InitializeNewInstance("android.app.job.JobInfo.Builder", Array(1, Me))
        job.RunMethod("setRequiresCharging", Array(False)) ' Define se precisa carregar
        job.RunMethod("setPeriodic", Array(12 * DateTime.TicksPerHour)) ' A cada 12 horas
        js.RunMethod("schedule", Array(job))
    Else
        ' Para dispositivos mais antigos, use AlarmManager
        Dim am As JavaObject
        am.InitializeStatic("android.app.AlarmManager")
        am.RunMethod("setRepeating", Array())
    End If
End Sub


ManifestEditor:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />

<application>
    <service android:name=".Starter" android:exported="true" />
    <service android:name=".TaskService" android:exported="true" />
</application>


This service performs the task of data collection and processing. TaskService.bas!
TaskService.bas:
Sub Process_Globals
    Private Notificacao As Notification
End Sub

Sub Service_Create
    Notificacao.Initialize
    Notificacao.Icon = "icon"
    Notificacao.SetInfo("Coleta de Dados", "Tarefa em execução", Main)
    Notificacao.Sound = True
End Sub

Sub Service_Start(StartingIntent As Intent)
    Log("Serviço de Coleta Iniciado")
    StartForeground(1, Notificacao) ' Garante que o serviço seja prioritário
    ExecutarTarefa
    StopService(Me) ' Finaliza após a execução
End Sub

Sub ExecutarTarefa
    ' Aqui você insere o código de coleta e processamento de dados
    Log("Coletando e processando dados...")
    ' Exemplo: enviar uma notificação ao usuário após concluir a tarefa
    Dim notificacaoConcluida As Notification
    notificacaoConcluida.Initialize
    notificacaoConcluida.Icon = "icon"
    notificacaoConcluida.SetInfo("Coleta Concluída", "Os dados foram processados.", Main)
    notificacaoConcluida.Sound = True
    notificacaoConcluida.Notify(1)
End Sub

Sub Service_Destroy
    Log("Serviço de Coleta Finalizado")
End Sub

This is the main service that initializes the app and configures schedules. Starter.bas
Starter.bas:
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
 
Upvote 0
Top