package io.appwrite.flutter.services import android.app.job.JobParameters import android.app.job.JobService import android.content.BroadcastReceiver import android.content.Context import android.content.Intent /** * The scheduled run of background push delivery: reconnects and re-arms itself. Scheduled * by the SDK; not meant to be started directly. */ class PushJobService : JobService() { override fun onStartJob(params: JobParameters): Boolean { // A chained job arms the next under the other chained id; the watchdog and an expedited // run (handed over by the alarm) only run once. Each stays up while missed messages arrive. val chained = params.jobId.takeIf { it == PushBackground.JOB_ID || it == PushBackground.NEXT_JOB_ID } PushBackground.tick(this, chained, PushBackground.JOB_DRAIN_MS) { jobFinished(params, false) } return true } // The run re-arms the next one itself, and the watchdog repeats on its own, so a stopped run // needs no retry. override fun onStopJob(params: JobParameters): Boolean = false } /** * The alarm that backs up the scheduled job when it runs late. Scheduled by the SDK; not meant * to be sent directly. */ class PushAlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action != PushBackground.ACTION_TICK) { return } // On Android 12+ the run goes to an expedited job, which keeps the process runnable while it // connects and the broker replays; it runs here when the system refuses one. if (PushBackground.runExpedited(context)) { return } val pending = goAsync() PushBackground.tick(context, drainMs = PushBackground.RECEIVER_DRAIN_MS) { pending.finish() } } } /** Resumes background push delivery after a reboot or an app update. */ class PushBootReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) { return } val pending = goAsync() PushBackground.tick(context) { pending.finish() } } }