app/src/main/java/dev/equwal/inkupdate/CheckJob.kt (2065 bytes)
1 // SPDX-License-Identifier: GPL-3.0-or-later 2 // Copyright (c) 2026 equwal 3 package dev.equwal.inkupdate 4 5 import android.app.job.JobInfo 6 import android.app.job.JobParameters 7 import android.app.job.JobScheduler 8 import android.app.job.JobService 9 import android.content.ComponentName 10 import android.content.Context 11 12 /** 13 * The daily check. 14 * 15 * The job is persisted, so it lives through a restart of the device. That is 16 * what the RECEIVE_BOOT_COMPLETED permission is for: the app has no receiver. 17 * The system decides the exact minute, and it waits for a network. 18 */ 19 class CheckJob : JobService() { 20 21 override fun onStartJob(params: JobParameters?): Boolean { 22 Thread { 23 val store = Store(applicationContext) 24 try { 25 Checker.checkAll(applicationContext, store) 26 } catch (e: Exception) { 27 store.checked(System.currentTimeMillis(), false) 28 } 29 jobFinished(params, false) 30 }.start() 31 // True: the work goes on after this function returns. 32 return true 33 } 34 35 override fun onStopJob(params: JobParameters?): Boolean = true 36 37 companion object { 38 39 private const val ID = 1 40 private const val DAY_MS = 24L * 60L * 60L * 1000L 41 42 /** Starts the daily job. A second call replaces the first. */ 43 fun schedule(context: Context) { 44 val s = context.getSystemService(JobScheduler::class.java) ?: return 45 val job = JobInfo.Builder(ID, ComponentName(context, CheckJob::class.java)) 46 .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) 47 .setPeriodic(DAY_MS) 48 .setPersisted(true) 49 .build() 50 try { 51 s.schedule(job) 52 } catch (e: Exception) { 53 // A device can refuse the job. The "Check now" button still works. 54 } 55 } 56 57 /** Stops the daily job. */ 58 fun cancel(context: Context) { 59 context.getSystemService(JobScheduler::class.java)?.cancel(ID) 60 } 61 } 62 }