2 * Copyright © 2021-2022 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Cell <https://www.stoutner.com/privacy-cell>.
6 * Privacy Cell is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Cell is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Cell. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacycell.workers
22 import android.content.Context
23 import android.content.Intent
25 import androidx.preference.PreferenceManager
26 import androidx.work.WorkManager
27 import androidx.work.Worker
28 import androidx.work.WorkerParameters
30 import com.stoutner.privacycell.R
31 import com.stoutner.privacycell.services.RealtimeMonitoringService
33 class RestartServiceWorker(appContext: Context, workerParameters: WorkerParameters) : Worker(appContext, workerParameters) {
34 override fun doWork(): Result {
35 // Get a handle for the shared preferences.
36 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
38 // Check to see if realtime monitoring is enabled. Sometimes the shared preferences can't return a value in time, because Android sucks.
39 // So, the default value is set to true, which is the safest value if the shared preferences can't be queried.
40 if (sharedPreferences.getBoolean(applicationContext.getString(R.string.realtime_monitoring_key), true)) { // Realtime monitoring is enabled.
41 // Start the realtime monitoring service as a foreground service, which is required because the worker is running in the background.
42 applicationContext.startForegroundService(Intent(applicationContext, RealtimeMonitoringService::class.java))
43 } else { // Realtime monitoring is disabled.
44 // Stop the realtime monitoring service.
45 applicationContext.stopService(Intent(applicationContext, RealtimeMonitoringService::class.java))
47 // Cancel the realtime listener work request.
48 WorkManager.getInstance(applicationContext).cancelUniqueWork(applicationContext.getString(R.string.register_listener_work_request))
52 return Result.success()