X-Git-Url: https://gitweb.stoutner.com/?p=PrivacyCell.git;a=blobdiff_plain;f=app%2Fsrc%2Fmain%2Fjava%2Fcom%2Fstoutner%2Fprivacycell%2Fworkers%2FRestartServiceWorker.kt;h=720ca7a937353ac758216d94250cc559904be230;hp=64b4eca93811a434e1e2d55349b18b1b2af16805;hb=86731d839decc4df39f2fa765f6727e64e151cb6;hpb=3191bf833c94b2462d4391ef913a2c2643632361 diff --git a/app/src/main/java/com/stoutner/privacycell/workers/RestartServiceWorker.kt b/app/src/main/java/com/stoutner/privacycell/workers/RestartServiceWorker.kt index 64b4eca..720ca7a 100644 --- a/app/src/main/java/com/stoutner/privacycell/workers/RestartServiceWorker.kt +++ b/app/src/main/java/com/stoutner/privacycell/workers/RestartServiceWorker.kt @@ -1,5 +1,5 @@ /* - * Copyright © 2021 Soren Stoutner . + * Copyright © 2021-2022 Soren Stoutner . * * This file is part of Privacy Cell . * @@ -22,14 +22,31 @@ package com.stoutner.privacycell.workers import android.content.Context import android.content.Intent +import androidx.preference.PreferenceManager +import androidx.work.WorkManager import androidx.work.Worker import androidx.work.WorkerParameters + +import com.stoutner.privacycell.R import com.stoutner.privacycell.services.RealtimeMonitoringService class RestartServiceWorker(appContext: Context, workerParameters: WorkerParameters) : Worker(appContext, workerParameters) { override fun doWork(): Result { - // Start the realtime monitoring service as a foreground service, which is required because the worker is running in the background. - applicationContext.startForegroundService(Intent(applicationContext, RealtimeMonitoringService::class.java)) + // Get a handle for the shared preferences. + val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) + + // Check to see if realtime monitoring is enabled. Sometimes the shared preferences can't return a value in time, because Android sucks. + // So, the default value is set to true, which is the safest value if the shared preferences can't be queried. + if (sharedPreferences.getBoolean(applicationContext.getString(R.string.realtime_monitoring_key), true)) { // Realtime monitoring is enabled. + // Start the realtime monitoring service as a foreground service, which is required because the worker is running in the background. + applicationContext.startForegroundService(Intent(applicationContext, RealtimeMonitoringService::class.java)) + } else { // Realtime monitoring is disabled. + // Stop the realtime monitoring service. + applicationContext.stopService(Intent(applicationContext, RealtimeMonitoringService::class.java)) + + // Cancel the realtime listener work request. + WorkManager.getInstance(applicationContext).cancelUniqueWork(applicationContext.getString(R.string.register_listener_work_request)) + } // Return a success. return Result.success()