LibreTube/app/src/main/java/com/github/libretube/helpers/NotificationHelper.kt

85 lines
2.7 KiB
Kotlin
Raw Normal View History

package com.github.libretube.helpers
2022-07-28 16:09:56 +05:30
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
2023-02-01 09:00:28 +05:30
import androidx.work.PeriodicWorkRequestBuilder
2022-07-28 16:09:56 +05:30
import androidx.work.WorkManager
2022-09-08 22:12:52 +05:30
import com.github.libretube.constants.NOTIFICATION_WORK_NAME
2022-09-08 21:59:00 +05:30
import com.github.libretube.constants.PreferenceKeys
2022-11-09 22:31:59 +05:30
import com.github.libretube.workers.NotificationWorker
2022-07-28 16:09:56 +05:30
import java.util.concurrent.TimeUnit
2022-11-06 14:51:37 +05:30
object NotificationHelper {
2022-08-20 13:12:24 +05:30
/**
* Enqueue the work manager task
*/
2022-07-28 16:09:56 +05:30
fun enqueueWork(
2022-11-06 14:51:37 +05:30
context: Context,
existingPeriodicWorkPolicy: ExistingPeriodicWorkPolicy,
2022-07-28 16:09:56 +05:30
) {
2022-07-28 19:28:22 +05:30
// get the notification preferences
2022-08-26 12:12:13 +05:30
PreferenceHelper.initialize(context)
2022-07-28 18:01:35 +05:30
val notificationsEnabled = PreferenceHelper.getBoolean(
PreferenceKeys.NOTIFICATION_ENABLED,
true,
2022-07-28 16:09:56 +05:30
)
2022-07-28 18:01:35 +05:30
val checkingFrequency = PreferenceHelper.getString(
PreferenceKeys.CHECKING_FREQUENCY,
"60",
2022-07-28 18:01:35 +05:30
).toLong()
2022-07-29 17:18:59 +05:30
// schedule the work manager request if logged in and notifications enabled
if (!notificationsEnabled) {
2022-07-29 17:18:59 +05:30
// cancel the work if notifications are disabled or the user is not logged in
2022-07-28 18:01:35 +05:30
WorkManager.getInstance(context)
2022-08-20 13:12:24 +05:30
.cancelUniqueWork(NOTIFICATION_WORK_NAME)
return
}
// required network type for the work
val networkType = when (
PreferenceHelper.getString(PreferenceKeys.REQUIRED_NETWORK, "all")
) {
"all" -> NetworkType.CONNECTED
"wifi" -> NetworkType.UNMETERED
"metered" -> NetworkType.METERED
else -> NetworkType.CONNECTED
2022-07-28 18:01:35 +05:30
}
// requirements for the work
// here: network needed to run the task
val constraints = Constraints.Builder()
.setRequiredNetworkType(networkType)
.build()
// create the worker
2023-02-01 09:00:28 +05:30
val notificationWorker = PeriodicWorkRequestBuilder<NotificationWorker>(
checkingFrequency,
TimeUnit.MINUTES,
)
.setConstraints(constraints)
.build()
// enqueue the task to the work manager instance
WorkManager.getInstance(context)
.enqueueUniquePeriodicWork(
NOTIFICATION_WORK_NAME,
existingPeriodicWorkPolicy,
notificationWorker,
)
// for testing the notifications by the work manager
/*
WorkManager.getInstance(context)
.enqueue(
OneTimeWorkRequest.Builder(NotificationWorker::class.java)
.setConstraints(constraints)
.build()
)
*/
2022-07-28 16:09:56 +05:30
}
}