Skip to content

Commit

Permalink
Update: Replace WorkHandler & WorkManager calls with inject
Browse files Browse the repository at this point in the history
  • Loading branch information
machiav3lli committed Dec 13, 2024
1 parent 0e9fd2d commit 9bcdc0e
Show file tree
Hide file tree
Showing 9 changed files with 56 additions and 50 deletions.
2 changes: 0 additions & 2 deletions src/main/java/com/machiav3lli/backup/OABX.kt
Original file line number Diff line number Diff line change
Expand Up @@ -476,8 +476,6 @@ class OABX : Application() {
}
}

val work: WorkHandler get() = NB.work

fun getString(resId: Int) = context.getString(resId)

fun minSDK(sdk: Int): Boolean {
Expand Down
17 changes: 9 additions & 8 deletions src/main/java/com/machiav3lli/backup/activities/MainActivityX.kt
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.dsl.module
import org.koin.java.KoinJavaComponent.get
import timber.log.Timber

@Composable
Expand Down Expand Up @@ -442,6 +443,7 @@ class MainActivityX : BaseActivity() {
val notificationId = now.toInt()
val batchType = getString(if (backupBoolean) R.string.backup else R.string.restore)
val batchName = WorkHandler.getBatchName(batchType, now)
val workManager = get<WorkManager>(WorkManager::class.java)

val selectedItems = selectedPackageNames
.mapIndexed { i, packageName ->
Expand All @@ -454,7 +456,7 @@ class MainActivityX : BaseActivity() {
var resultsSuccess = true
var counter = 0
val worksList: MutableList<OneTimeWorkRequest> = mutableListOf()
OABX.work.beginBatch(batchName)
get<WorkHandler>(WorkHandler::class.java).beginBatch(batchName)
selectedItems.forEach { (packageName, mode) ->

val oneTimeWorkRequest =
Expand All @@ -468,8 +470,7 @@ class MainActivityX : BaseActivity() {
)
worksList.add(oneTimeWorkRequest)

val oneTimeWorkLiveData = WorkManager.getInstance(OABX.context)
.getWorkInfoByIdLiveData(oneTimeWorkRequest.id)
val oneTimeWorkLiveData = workManager.getWorkInfoByIdLiveData(oneTimeWorkRequest.id)
oneTimeWorkLiveData.observeForever(
object : Observer<WorkInfo?> { //TODO WECH hg42
override fun onChanged(value: WorkInfo?) {
Expand Down Expand Up @@ -498,7 +499,7 @@ class MainActivityX : BaseActivity() {
}

if (worksList.isNotEmpty()) {
WorkManager.getInstance(OABX.context)
workManager
.beginWith(worksList)
.enqueue()
}
Expand All @@ -513,6 +514,7 @@ class MainActivityX : BaseActivity() {
val notificationId = now.toInt()
val batchType = getString(R.string.restore)
val batchName = WorkHandler.getBatchName(batchType, now)
val workManager = get<WorkManager>(WorkManager::class.java)

val selectedItems = buildList {
selectedPackageNames.forEach { pn ->
Expand All @@ -537,7 +539,7 @@ class MainActivityX : BaseActivity() {
var resultsSuccess = true
var counter = 0
val worksList: MutableList<OneTimeWorkRequest> = mutableListOf()
OABX.work.beginBatch(batchName)
get<WorkHandler>(WorkHandler::class.java).beginBatch(batchName)
selectedItems.forEach { (packageName, bi, mode) ->
val oneTimeWorkRequest = AppActionWork.Request(
packageName = packageName,
Expand All @@ -550,8 +552,7 @@ class MainActivityX : BaseActivity() {
)
worksList.add(oneTimeWorkRequest)

val oneTimeWorkLiveData = WorkManager.getInstance(OABX.context)
.getWorkInfoByIdLiveData(oneTimeWorkRequest.id)
val oneTimeWorkLiveData = workManager.getWorkInfoByIdLiveData(oneTimeWorkRequest.id)
oneTimeWorkLiveData.observeForever(
object : Observer<WorkInfo?> {
override fun onChanged(value: WorkInfo?) {
Expand Down Expand Up @@ -580,7 +581,7 @@ class MainActivityX : BaseActivity() {
}

if (worksList.isNotEmpty()) {
WorkManager.getInstance(OABX.context)
workManager
.beginWith(worksList)
.enqueue()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,15 @@ class ScheduleRepository(
)
} else {
traceSchedule { "[$schedule.id] ScheduleViewModel.updateS -> cancelAlarm" }
ScheduleWork.cancel(appContext, schedule.id)
ScheduleWork.cancel(schedule.id)
}
}
}

suspend fun deleteById(id: Long) {
withContext(Dispatchers.IO) {
db.getScheduleDao().deleteById(id)
ScheduleWork.cancel(appContext, id)
ScheduleWork.cancel(id)
}
}
}
Expand Down
31 changes: 20 additions & 11 deletions src/main/java/com/machiav3lli/backup/handler/WorkHandler.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.machiav3lli.backup.handler

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
Expand All @@ -24,22 +26,20 @@ import com.machiav3lli.backup.preferences.pref_maxRetriesPerPackage
import com.machiav3lli.backup.services.CommandReceiver
import com.machiav3lli.backup.tasks.AppActionWork
import com.machiav3lli.backup.utils.SystemUtils
import org.koin.java.KoinJavaComponent.get
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.Locale

var actionReceiver: CommandReceiver
var context: Context = appContext
val notificationManager: NotificationManagerCompat
val notificationChannel: NotificationChannel
class WorkHandler(
private val context: Context,
private val manager: WorkManager,
) {
private val actionReceiver = CommandReceiver()
private val notificationChannel: NotificationChannel
private val notificationManager: NotificationManagerCompat

init {
actionReceiver = CommandReceiver()

context.registerReceiver(actionReceiver, IntentFilter())

notificationManager = NotificationManagerCompat.from(context)
Expand Down Expand Up @@ -82,7 +82,7 @@ class WorkHandler(

fun endBatches() {
Timber.d("%%%%% ALL PRUNE")
OABX.work.prune()
get<WorkHandler>(WorkHandler::class.java).prune()

// delete all batches started a long time ago (e.g. a day)
val longAgo = 24 * 60 * 60 * 1000
Expand Down Expand Up @@ -146,6 +146,13 @@ class WorkHandler(
}
}

@SuppressLint("MissingPermission")
fun notify(notificationId: Int, notification: Notification) =
notificationManager.notify(
notificationId,
notification,
)

companion object {

fun getBatchName(name: String, startTime: Long): String {
Expand Down Expand Up @@ -520,15 +527,16 @@ class WorkHandler(
}

val notification = notificationBuilder.build()
val workHandler = get<WorkHandler>(WorkHandler::class.java)
Timber.d("%%%%%%%%%%%%%%%%%%%%> $batchName ${batch.notificationId} '$shortText' $notification")
OABX.work.notificationManager.notify(
workHandler.notify(
batch.notificationId,
notification
)

if (remaining <= 0) {
if (batch.nFinished == 0)
OABX.work.endBatch(batchName)
workHandler.endBatch(batchName)
batch.nFinished += 1
}
}
Expand All @@ -541,9 +549,10 @@ class WorkHandler(
} else {
packagesState.clear()
OABX.setProgress()
if (OABX.work.justFinishedAll()) {
val workHandler = get<WorkHandler>(WorkHandler::class.java)
if (workHandler.justFinishedAll()) {
Timber.d("%%%%% ALL $batchesStarted batches, thread ${Thread.currentThread().id}")
OABX.work.endBatches()
workHandler.endBatches()
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/com/machiav3lli/backup/pages/SchedulePage.kt
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ import com.machiav3lli.backup.LaunchableFilter
import com.machiav3lli.backup.MAIN_FILTER_DEFAULT
import com.machiav3lli.backup.MAIN_FILTER_DEFAULT_WITHOUT_SPECIAL
import com.machiav3lli.backup.MODE_UNSET
import com.machiav3lli.backup.OABX
import com.machiav3lli.backup.R
import com.machiav3lli.backup.UpdatedFilter
import com.machiav3lli.backup.dbs.entity.Schedule
Expand Down Expand Up @@ -491,7 +490,7 @@ fun SchedulePage(
primaryText = stringResource(R.string.dialogOK),
primaryAction = {
if (schedule.mode != MODE_UNSET)
ScheduleWork.enqueueImmediate(OABX.context, schedule)
ScheduleWork.enqueueImmediate(schedule)
},
)

Expand Down
3 changes: 1 addition & 2 deletions src/main/java/com/machiav3lli/backup/pages/SchedulerPage.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ import androidx.compose.ui.res.stringResource
import com.machiav3lli.backup.DialogMode
import com.machiav3lli.backup.ICON_SIZE_SMALL
import com.machiav3lli.backup.MODE_UNSET
import com.machiav3lli.backup.OABX
import com.machiav3lli.backup.R
import com.machiav3lli.backup.dbs.entity.Schedule
import com.machiav3lli.backup.dialogs.ActionsDialogUI
Expand Down Expand Up @@ -146,7 +145,7 @@ fun SchedulerPage(viewModel: SchedulesVM = koinViewModel()) {
primaryText = stringResource(R.string.dialogOK),
primaryAction = {
if (schedule.mode != MODE_UNSET)
ScheduleWork.enqueueImmediate(OABX.context, schedule)
ScheduleWork.enqueueImmediate(schedule)
},
)

Expand Down
12 changes: 7 additions & 5 deletions src/main/java/com/machiav3lli/backup/services/CommandReceiver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import com.machiav3lli.backup.EXTRA_PERIODIC
import com.machiav3lli.backup.EXTRA_SCHEDULE_ID
import com.machiav3lli.backup.OABX
import com.machiav3lli.backup.dbs.repository.ScheduleRepository
import com.machiav3lli.backup.handler.WorkHandler
import com.machiav3lli.backup.preferences.traceSchedule
import com.machiav3lli.backup.tasks.ScheduleWork
import com.machiav3lli.backup.utils.SystemUtils
Expand All @@ -21,6 +22,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.java.KoinJavaComponent.get
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.Locale
Expand All @@ -41,16 +43,16 @@ class CommandReceiver : //TODO hg42 how to maintain security?
val batchName = intent.getStringExtra("name")
Timber.d("################################################### command intent cancel -------------> name=$batchName")
OABX.addInfoLogText("$command $batchName")
OABX.work.cancel(batchName)
get<WorkHandler>(WorkHandler::class.java).cancel(batchName)
}

ACTION_RUN_SCHEDULE -> {
ACTION_RUN_SCHEDULE -> {
intent.getStringExtra("name")?.let { name ->
OABX.addInfoLogText("$command $name")
Timber.d("################################################### command intent schedule -------------> name=$name")
CoroutineScope(Dispatchers.Default).launch {
scheduleRepo.getSchedule(name)?.let { schedule ->
ScheduleWork.enqueueImmediate(context, schedule)
ScheduleWork.enqueueImmediate(schedule)
}
}
}
Expand All @@ -59,11 +61,11 @@ class CommandReceiver : //TODO hg42 how to maintain security?
ACTION_CANCEL_SCHEDULE -> {
intent.getLongExtra(EXTRA_SCHEDULE_ID, -1L).takeIf { it != -1L }?.let { id ->
Timber.d("################################################### command cancel schedule -------------> id=$id")
ScheduleWork.cancel(context, id, intent.getBooleanExtra(EXTRA_PERIODIC, false))
ScheduleWork.cancel(id, intent.getBooleanExtra(EXTRA_PERIODIC, false))
}
}

ACTION_RE_SCHEDULE -> { // TODO reconsider when ScheduleWork is fully implemented
ACTION_RE_SCHEDULE -> { // TODO reconsider when ScheduleWork is fully implemented
intent.getStringExtra("name")?.let { name ->
val now = SystemUtils.now
val time = intent.getStringExtra("time")
Expand Down
30 changes: 14 additions & 16 deletions src/main/java/com/machiav3lli/backup/tasks/ScheduleWork.kt
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ class ScheduleWork(
notificationManager.cancel(notificationId)

val batchName = WorkHandler.getBatchName(name, now)
OABX.work.beginBatch(batchName)
get<WorkHandler>(WorkHandler::class.java).beginBatch(batchName)

var errors = ""
var resultsSuccess = true
Expand All @@ -184,7 +184,7 @@ class ScheduleWork(
scheduleRepo.update(schedule.copy(timePlaced = now))

async {
OABX.work.manager.getWorkInfoByIdFlow(oneTimeWorkRequest.id)
get<WorkManager>(WorkManager::class.java).getWorkInfoByIdFlow(oneTimeWorkRequest.id)
.collectLatest { workInfo ->
when (workInfo?.state) {
androidx.work.WorkInfo.State.SUCCEEDED,
Expand Down Expand Up @@ -220,7 +220,7 @@ class ScheduleWork(

if (worksList.isNotEmpty()) {
if (beginSchedule(name, "queueing work")) {
OABX.work.manager
get<WorkManager>(WorkManager::class.java)
.beginWith(worksList)
.enqueue()
workJobs.awaitAll()
Expand Down Expand Up @@ -382,9 +382,9 @@ class ScheduleWork(
private const val SCHEDULE_WORK = "schedule_work_"
private val runningSchedules = ConcurrentHashMap<Long, Boolean>()

fun enqueuePeriodic(context: Context, schedule: Schedule, reschedule: Boolean = false) {
fun enqueuePeriodic(schedule: Schedule, reschedule: Boolean = false) {
if (!schedule.enabled) return
val workManager = WorkManager.getInstance(context)
val workManager = get<WorkManager>(WorkManager::class.java)

val (timeToRun, initialDelay) = calcRuntimeDiff(schedule)

Expand Down Expand Up @@ -426,9 +426,7 @@ class ScheduleWork(
}
}

fun enqueueImmediate(context: Context, schedule: Schedule) {
val workManager = WorkManager.getInstance(context)

fun enqueueImmediate(schedule: Schedule) {
val scheduleWorkRequest = OneTimeWorkRequestBuilder<ScheduleWork>()
.setInputData(
workDataOf(
Expand All @@ -441,7 +439,7 @@ class ScheduleWork(
.addTag("schedule_${schedule.id}")
.build()

workManager.enqueueUniqueWork(
get<WorkManager>(WorkManager::class.java).enqueueUniqueWork(
"$SCHEDULE_ONETIME${schedule.id}",
ExistingWorkPolicy.REPLACE,
scheduleWorkRequest,
Expand All @@ -451,7 +449,7 @@ class ScheduleWork(
}
}

fun scheduleAll(context: Context) {
fun scheduleAll() {
Thread {
val scheduleRepo = get<ScheduleRepository>(ScheduleRepository::class.java)
val workManager = get<WorkManager>(WorkManager::class.java)
Expand All @@ -465,24 +463,24 @@ class ScheduleWork(
traceSchedule { "[${schedule.id}]: ignore $schedule" }
}

schedule.enabled -> {
schedule.enabled -> {
traceSchedule { "[${schedule.id}]: enable $schedule" }
enqueuePeriodic(context, schedule, false)
enqueuePeriodic(schedule, false)
}

else -> {
else -> {
traceSchedule { "[${schedule.id}]: cancel $schedule" }
cancel(context, schedule.id, true)
cancel(schedule.id, true)
}
}
}
workManager.pruneWork()
}.start()
}

fun cancel(context: Context, scheduleId: Long, periodic: Boolean = true) {
fun cancel(scheduleId: Long, periodic: Boolean = true) {
traceSchedule { "[$scheduleId]: Canceling" }
WorkManager.getInstance(context)
get<WorkManager>(WorkManager::class.java)
.cancelUniqueWork(
"${if (periodic) SCHEDULE_WORK else SCHEDULE_ONETIME}$scheduleId"
)
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/machiav3lli/backup/utils/ScheduleUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ fun scheduleNext(context: Context, scheduleId: Long, rescheduleBoolean: Boolean)
traceSchedule { "[${schedule.id}] re-scheduling $schedule" }
scheduleRepo.update(schedule)
}
ScheduleWork.enqueuePeriodic(context, schedule, rescheduleBoolean)
ScheduleWork.enqueuePeriodic(schedule, rescheduleBoolean)
}
} else {
Timber.e("[$scheduleId] got id from $context")
Expand All @@ -167,7 +167,7 @@ fun scheduleAlarmsOnce() { // TODO replace with ScheduleWorker.scheduleAll()
if (alarmsHaveBeenScheduled)
return
alarmsHaveBeenScheduled = true
ScheduleWork.scheduleAll(OABX.context)
ScheduleWork.scheduleAll()
}

fun Context.getStartScheduleMessage(schedule: Schedule) = StringBuilder()
Expand Down

0 comments on commit 9bcdc0e

Please sign in to comment.