Refactor and optimize PreferencesHelper

This commit is contained in:
TacoTheDank 2021-07-01 15:11:08 -04:00
parent c81105186f
commit 09012a35a7
11 changed files with 91 additions and 102 deletions

View file

@ -17,7 +17,6 @@
package org.y20k.trackbook package org.y20k.trackbook
import android.content.Context
import android.content.SharedPreferences import android.content.SharedPreferences
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
@ -26,7 +25,6 @@ import android.os.StrictMode.VmPolicy
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController import androidx.navigation.ui.setupWithNavController
import androidx.preference.PreferenceManager
import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.bottomnavigation.BottomNavigationView
import org.osmdroid.config.Configuration import org.osmdroid.config.Configuration
import org.y20k.trackbook.helpers.AppThemeHelper import org.y20k.trackbook.helpers.AppThemeHelper
@ -91,7 +89,7 @@ class MainActivity : AppCompatActivity() {
} }
// register listener for changes in shared preferences // register listener for changes in shared preferences
PreferenceManager.getDefaultSharedPreferences(this as Context).registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener) PreferencesHelper.registerPreferenceChangeListener(sharedPreferenceChangeListener)
} }
@ -99,7 +97,7 @@ class MainActivity : AppCompatActivity() {
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
// unregister listener for changes in shared preferences // unregister listener for changes in shared preferences
PreferenceManager.getDefaultSharedPreferences(this as Context).unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener) PreferencesHelper.unregisterPreferenceChangeListener(sharedPreferenceChangeListener)
} }
@ -109,7 +107,7 @@ class MainActivity : AppCompatActivity() {
private val sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key -> private val sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
when (key) { when (key) {
Keys.PREF_THEME_SELECTION -> { Keys.PREF_THEME_SELECTION -> {
AppThemeHelper.setTheme(PreferencesHelper.loadThemeSelection(this@MainActivity)) AppThemeHelper.setTheme(PreferencesHelper.loadThemeSelection())
} }
} }
} }

View file

@ -32,7 +32,6 @@ import android.view.ViewGroup
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import androidx.preference.PreferenceManager
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Dispatchers.Main
@ -71,7 +70,7 @@ class MapFragment : Fragment(), YesNoDialog.YesNoDialogListener, MapOverlayHelpe
// get current best location // get current best location
currentBestLocation = LocationHelper.getLastKnownLocation(activity as Context) currentBestLocation = LocationHelper.getLastKnownLocation(activity as Context)
// get saved tracking state // get saved tracking state
trackingState = PreferencesHelper.loadTrackingState(activity as Context) trackingState = PreferencesHelper.loadTrackingState()
} }
@ -260,7 +259,7 @@ class MapFragment : Fragment(), YesNoDialog.YesNoDialogListener, MapOverlayHelpe
private fun handleServiceUnbind() { private fun handleServiceUnbind() {
bound = false bound = false
// unregister listener for changes in shared preferences // unregister listener for changes in shared preferences
PreferenceManager.getDefaultSharedPreferences(activity as Context).unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener) PreferencesHelper.unregisterPreferenceChangeListener(sharedPreferenceChangeListener)
// stop receiving location updates // stop receiving location updates
handler.removeCallbacks(periodicLocationRequestRunnable) handler.removeCallbacks(periodicLocationRequestRunnable)
} }
@ -319,7 +318,7 @@ class MapFragment : Fragment(), YesNoDialog.YesNoDialogListener, MapOverlayHelpe
when (key) { when (key) {
Keys.PREF_TRACKING_STATE -> { Keys.PREF_TRACKING_STATE -> {
if (activity != null) { if (activity != null) {
trackingState = PreferencesHelper.loadTrackingState(activity as Context) trackingState = PreferencesHelper.loadTrackingState()
layout.updateRecordingButton(trackingState) layout.updateRecordingButton(trackingState)
} }
} }
@ -343,7 +342,7 @@ class MapFragment : Fragment(), YesNoDialog.YesNoDialogListener, MapOverlayHelpe
trackingState = trackerService.trackingState trackingState = trackerService.trackingState
layout.updateRecordingButton(trackingState) layout.updateRecordingButton(trackingState)
// register listener for changes in shared preferences // register listener for changes in shared preferences
PreferenceManager.getDefaultSharedPreferences(activity as Context).registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener) PreferencesHelper.registerPreferenceChangeListener(sharedPreferenceChangeListener)
// start listening for location updates // start listening for location updates
handler.removeCallbacks(periodicLocationRequestRunnable) handler.removeCallbacks(periodicLocationRequestRunnable)
handler.postDelayed(periodicLocationRequestRunnable, 0) handler.postDelayed(periodicLocationRequestRunnable, 0)

View file

@ -22,6 +22,7 @@ import android.app.Application
import org.y20k.trackbook.helpers.AppThemeHelper import org.y20k.trackbook.helpers.AppThemeHelper
import org.y20k.trackbook.helpers.LogHelper import org.y20k.trackbook.helpers.LogHelper
import org.y20k.trackbook.helpers.PreferencesHelper import org.y20k.trackbook.helpers.PreferencesHelper
import org.y20k.trackbook.helpers.PreferencesHelper.initPreferences
/* /*
@ -38,8 +39,9 @@ class Trackbook: Application() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
LogHelper.v(TAG, "Trackbook application started.") LogHelper.v(TAG, "Trackbook application started.")
initPreferences()
// set Dark / Light theme state // set Dark / Light theme state
AppThemeHelper.setTheme(PreferencesHelper.loadThemeSelection(this)) AppThemeHelper.setTheme(PreferencesHelper.loadThemeSelection())
} }

View file

@ -37,7 +37,6 @@ import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.IBinder import android.os.IBinder
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.preference.PreferenceManager
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.IO
import org.y20k.trackbook.core.Track import org.y20k.trackbook.core.Track
@ -83,9 +82,9 @@ class TrackerService: Service(), SensorEventListener {
/* Overrides onCreate from Service */ /* Overrides onCreate from Service */
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
gpsOnly = PreferencesHelper.loadGpsOnly(this) gpsOnly = PreferencesHelper.loadGpsOnly()
useImperial = PreferencesHelper.loadUseImperialUnits(this) useImperial = PreferencesHelper.loadUseImperialUnits()
accuracyMultiplier = PreferencesHelper.loadAccuracyMultiplier(this) accuracyMultiplier = PreferencesHelper.loadAccuracyMultiplier()
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
sensorManager = this.getSystemService(Context.SENSOR_SERVICE) as SensorManager sensorManager = this.getSystemService(Context.SENSOR_SERVICE) as SensorManager
@ -95,11 +94,11 @@ class TrackerService: Service(), SensorEventListener {
networkProviderActive = LocationHelper.isNetworkEnabled(locationManager) networkProviderActive = LocationHelper.isNetworkEnabled(locationManager)
gpsLocationListener = createLocationListener() gpsLocationListener = createLocationListener()
networkLocationListener = createLocationListener() networkLocationListener = createLocationListener()
trackingState = PreferencesHelper.loadTrackingState(this) trackingState = PreferencesHelper.loadTrackingState()
currentBestLocation = LocationHelper.getLastKnownLocation(this) currentBestLocation = LocationHelper.getLastKnownLocation(this)
track = FileHelper.readTrack(this, FileHelper.getTempFileUri(this)) track = FileHelper.readTrack(this, FileHelper.getTempFileUri(this))
altitudeValues.capacity = PreferencesHelper.loadAltitudeSmoothingValue(this) altitudeValues.capacity = PreferencesHelper.loadAltitudeSmoothingValue()
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener( PreferencesHelper.registerPreferenceChangeListener(
sharedPreferenceChangeListener sharedPreferenceChangeListener
) )
} }
@ -175,7 +174,7 @@ class TrackerService: Service(), SensorEventListener {
// remove notification // remove notification
stopForeground(true) stopForeground(true)
// stop listening for changes in shared preferences // stop listening for changes in shared preferences
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener( PreferencesHelper.unregisterPreferenceChangeListener(
sharedPreferenceChangeListener sharedPreferenceChangeListener
) )
// stop receiving location updates // stop receiving location updates
@ -239,7 +238,7 @@ class TrackerService: Service(), SensorEventListener {
} }
// set state // set state
trackingState = Keys.STATE_TRACKING_ACTIVE trackingState = Keys.STATE_TRACKING_ACTIVE
PreferencesHelper.saveTrackingState(this, trackingState) PreferencesHelper.saveTrackingState(trackingState)
// start recording steps and location fixes // start recording steps and location fixes
startStepCounter() startStepCounter()
handler.postDelayed(periodicTrackUpdate, 0) handler.postDelayed(periodicTrackUpdate, 0)
@ -255,7 +254,7 @@ class TrackerService: Service(), SensorEventListener {
CoroutineScope(IO).launch { FileHelper.saveTempTrackSuspended(this@TrackerService, track) } CoroutineScope(IO).launch { FileHelper.saveTempTrackSuspended(this@TrackerService, track) }
// save state // save state
trackingState = Keys.STATE_TRACKING_STOPPED trackingState = Keys.STATE_TRACKING_STOPPED
PreferencesHelper.saveTrackingState(this, trackingState) PreferencesHelper.saveTrackingState(trackingState)
// reset altitude values queue // reset altitude values queue
altitudeValues.reset() altitudeValues.reset()
// stop recording steps and location fixes // stop recording steps and location fixes
@ -272,7 +271,7 @@ class TrackerService: Service(), SensorEventListener {
track = Track() track = Track()
FileHelper.deleteTempFile(this) FileHelper.deleteTempFile(this)
trackingState = Keys.STATE_TRACKING_NOT trackingState = Keys.STATE_TRACKING_NOT
PreferencesHelper.saveTrackingState(this, trackingState) PreferencesHelper.saveTrackingState(trackingState)
stopForeground(true) stopForeground(true)
} }
@ -469,7 +468,7 @@ class TrackerService: Service(), SensorEventListener {
when (key) { when (key) {
// preference "Restrict to GPS" // preference "Restrict to GPS"
Keys.PREF_GPS_ONLY -> { Keys.PREF_GPS_ONLY -> {
gpsOnly = PreferencesHelper.loadGpsOnly(this@TrackerService) gpsOnly = PreferencesHelper.loadGpsOnly()
when (gpsOnly) { when (gpsOnly) {
true -> removeNetworkLocationListener() true -> removeNetworkLocationListener()
false -> addNetworkLocationListener() false -> addNetworkLocationListener()
@ -477,11 +476,11 @@ class TrackerService: Service(), SensorEventListener {
} }
// preference "Use Imperial Measurements" // preference "Use Imperial Measurements"
Keys.PREF_USE_IMPERIAL_UNITS -> { Keys.PREF_USE_IMPERIAL_UNITS -> {
useImperial = PreferencesHelper.loadUseImperialUnits(this@TrackerService) useImperial = PreferencesHelper.loadUseImperialUnits()
} }
// preference "Recording Accuracy" // preference "Recording Accuracy"
Keys.PREF_RECORDING_ACCURACY_HIGH -> { Keys.PREF_RECORDING_ACCURACY_HIGH -> {
accuracyMultiplier = PreferencesHelper.loadAccuracyMultiplier(this@TrackerService) accuracyMultiplier = PreferencesHelper.loadAccuracyMultiplier()
} }
} }
} }

View file

@ -23,7 +23,6 @@ import android.graphics.drawable.Icon
import android.os.Build import android.os.Build
import android.service.quicksettings.Tile import android.service.quicksettings.Tile
import android.service.quicksettings.TileService import android.service.quicksettings.TileService
import androidx.preference.PreferenceManager
import org.y20k.trackbook.helpers.LogHelper import org.y20k.trackbook.helpers.LogHelper
import org.y20k.trackbook.helpers.PreferencesHelper import org.y20k.trackbook.helpers.PreferencesHelper
@ -47,7 +46,7 @@ class TrackingToggleTileService: TileService() {
override fun onTileAdded() { override fun onTileAdded() {
super.onTileAdded() super.onTileAdded()
// get saved tracking state // get saved tracking state
trackingState = PreferencesHelper.loadTrackingState(this) trackingState = PreferencesHelper.loadTrackingState()
// set up tile // set up tile
updateTile() updateTile()
} }
@ -62,11 +61,11 @@ class TrackingToggleTileService: TileService() {
override fun onStartListening() { override fun onStartListening() {
super.onStartListening() super.onStartListening()
// get saved tracking state // get saved tracking state
trackingState = PreferencesHelper.loadTrackingState(this) trackingState = PreferencesHelper.loadTrackingState()
// set up tile // set up tile
updateTile() updateTile()
// register listener for changes in shared preferences // register listener for changes in shared preferences
PreferenceManager.getDefaultSharedPreferences(this@TrackingToggleTileService).registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener) PreferencesHelper.registerPreferenceChangeListener(sharedPreferenceChangeListener)
} }
@ -84,7 +83,7 @@ class TrackingToggleTileService: TileService() {
override fun onStopListening() { override fun onStopListening() {
super.onStopListening() super.onStopListening()
// unregister listener for changes in shared preferences // unregister listener for changes in shared preferences
PreferenceManager.getDefaultSharedPreferences(this@TrackingToggleTileService).unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener) PreferencesHelper.unregisterPreferenceChangeListener(sharedPreferenceChangeListener)
} }
@ -141,7 +140,7 @@ class TrackingToggleTileService: TileService() {
private val sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key -> private val sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
when (key) { when (key) {
Keys.PREF_TRACKING_STATE -> { Keys.PREF_TRACKING_STATE -> {
trackingState = PreferencesHelper.loadTrackingState(this) trackingState = PreferencesHelper.loadTrackingState()
updateTile() updateTile()
} }
} }

View file

@ -77,7 +77,7 @@ object AppThemeHelper {
/* Returns a readable String for currently selected App Theme */ /* Returns a readable String for currently selected App Theme */
fun getCurrentTheme(context: Context): String { fun getCurrentTheme(context: Context): String {
return when (PreferencesHelper.loadThemeSelection(context)) { return when (PreferencesHelper.loadThemeSelection()) {
Keys.STATE_THEME_LIGHT_MODE -> context.getString(R.string.pref_theme_selection_mode_light) Keys.STATE_THEME_LIGHT_MODE -> context.getString(R.string.pref_theme_selection_mode_light)
Keys.STATE_THEME_DARK_MODE -> context.getString(R.string.pref_theme_selection_mode_dark) Keys.STATE_THEME_DARK_MODE -> context.getString(R.string.pref_theme_selection_mode_dark)
else -> context.getString(R.string.pref_theme_selection_mode_device_default) else -> context.getString(R.string.pref_theme_selection_mode_device_default)

View file

@ -62,7 +62,7 @@ object LocationHelper {
/* Tries to return the last location that the system has stored */ /* Tries to return the last location that the system has stored */
fun getLastKnownLocation(context: Context): Location { fun getLastKnownLocation(context: Context): Location {
// get last location that Trackbook has stored // get last location that Trackbook has stored
var lastKnownLocation: Location = PreferencesHelper.loadCurrentBestLocation(context) var lastKnownLocation: Location = PreferencesHelper.loadCurrentBestLocation()
// try to get the last location the system has stored - it is probably more recent // try to get the last location the system has stored - it is probably more recent
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager

View file

@ -18,6 +18,7 @@
package org.y20k.trackbook.helpers package org.y20k.trackbook.helpers
import android.content.Context import android.content.Context
import android.content.SharedPreferences
import android.location.Location import android.location.Location
import android.location.LocationManager import android.location.LocationManager
import androidx.core.content.edit import androidx.core.content.edit
@ -32,124 +33,108 @@ import org.y20k.trackbook.extensions.putDouble
*/ */
object PreferencesHelper { object PreferencesHelper {
/* The sharedPreferences object to be initialized */
private lateinit var sharedPreferences: SharedPreferences
/* Initialize a single sharedPreferences object when the app is launched */
fun Context.initPreferences() {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
}
/* Define log tag */ /* Define log tag */
private val TAG: String = LogHelper.makeLogTag(PreferencesHelper::class.java) private val TAG: String = LogHelper.makeLogTag(PreferencesHelper::class.java)
/* Loads zoom level of map */ /* Loads zoom level of map */
fun loadZoomLevel(context: Context): Double { fun loadZoomLevel(): Double {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// load zoom level // load zoom level
return settings.getDouble(Keys.PREF_MAP_ZOOM_LEVEL, Keys.DEFAULT_ZOOM_LEVEL) return sharedPreferences.getDouble(Keys.PREF_MAP_ZOOM_LEVEL, Keys.DEFAULT_ZOOM_LEVEL)
} }
/* Saves zoom level of map */ /* Saves zoom level of map */
fun saveZoomLevel(context: Context, zoomLevel: Double) { fun saveZoomLevel(zoomLevel: Double) {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// save zoom level // save zoom level
settings.edit { putDouble(Keys.PREF_MAP_ZOOM_LEVEL, zoomLevel) } sharedPreferences.edit { putDouble(Keys.PREF_MAP_ZOOM_LEVEL, zoomLevel) }
} }
/* Loads tracking state */ /* Loads tracking state */
fun loadTrackingState(context: Context): Int { fun loadTrackingState(): Int {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// load tracking state // load tracking state
return settings.getInt(Keys.PREF_TRACKING_STATE, Keys.STATE_TRACKING_NOT) return sharedPreferences.getInt(Keys.PREF_TRACKING_STATE, Keys.STATE_TRACKING_NOT)
} }
/* Saves tracking state */ /* Saves tracking state */
fun saveTrackingState(context: Context, trackingState: Int) { fun saveTrackingState(trackingState: Int) {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// save tracking state // save tracking state
settings.edit { putInt(Keys.PREF_TRACKING_STATE, trackingState) } sharedPreferences.edit { putInt(Keys.PREF_TRACKING_STATE, trackingState) }
} }
/* Loads length unit system - metric or imperial */ /* Loads length unit system - metric or imperial */
fun loadUseImperialUnits(context: Context): Boolean { fun loadUseImperialUnits(): Boolean {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// load length unit system // load length unit system
return settings.getBoolean(Keys.PREF_USE_IMPERIAL_UNITS, LengthUnitHelper.useImperialUnits()) return sharedPreferences.getBoolean(Keys.PREF_USE_IMPERIAL_UNITS, LengthUnitHelper.useImperialUnits())
} }
/* Loads length unit system - metric or imperial */ /* Loads length unit system - metric or imperial */
fun loadGpsOnly(context: Context): Boolean { fun loadGpsOnly(): Boolean {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// load length unit system // load length unit system
return settings.getBoolean(Keys.PREF_GPS_ONLY, false) return sharedPreferences.getBoolean(Keys.PREF_GPS_ONLY, false)
} }
/* Loads accuracy threshold used to determine if location is good enough */ /* Loads accuracy threshold used to determine if location is good enough */
fun loadAccuracyThreshold(context: Context): Int { fun loadAccuracyThreshold(): Int {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// load tracking state // load tracking state
return settings.getInt(Keys.PREF_LOCATION_ACCURACY_THRESHOLD, Keys.DEFAULT_THRESHOLD_LOCATION_ACCURACY) return sharedPreferences.getInt(Keys.PREF_LOCATION_ACCURACY_THRESHOLD, Keys.DEFAULT_THRESHOLD_LOCATION_ACCURACY)
} }
/* Loads state of recording accuracy */ /* Loads state of recording accuracy */
fun loadRecordingAccuracyHigh(context: Context): Boolean { fun loadRecordingAccuracyHigh(): Boolean {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// load current setting // load current setting
return settings.getBoolean(Keys.PREF_RECORDING_ACCURACY_HIGH, false) return sharedPreferences.getBoolean(Keys.PREF_RECORDING_ACCURACY_HIGH, false)
} }
/* Loads current accuracy multiplier */ /* Loads current accuracy multiplier */
fun loadAccuracyMultiplier(context: Context): Int { fun loadAccuracyMultiplier(): Int {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// load current setting // load current setting
val recordingAccuracyHigh: Boolean = settings.getBoolean(Keys.PREF_RECORDING_ACCURACY_HIGH, false) val recordingAccuracyHigh: Boolean = sharedPreferences.getBoolean(Keys.PREF_RECORDING_ACCURACY_HIGH, false)
// return multiplier based on state // return multiplier based on state
return if (recordingAccuracyHigh) 2 else 1 return if (recordingAccuracyHigh) 2 else 1
} }
/* Load altitude smoothing value */ /* Load altitude smoothing value */
fun loadAltitudeSmoothingValue(context: Context): Int { fun loadAltitudeSmoothingValue(): Int {
// get preferences
val settings = PreferenceManager.getDefaultSharedPreferences(context)
// load current setting // load current setting
return settings.getInt(Keys.PREF_ALTITUDE_SMOOTHING_VALUE, Keys.DEFAULT_ALTITUDE_SMOOTHING_VALUE) return sharedPreferences.getInt(Keys.PREF_ALTITUDE_SMOOTHING_VALUE, Keys.DEFAULT_ALTITUDE_SMOOTHING_VALUE)
} }
/* Loads the state of a map */ /* Loads the state of a map */
fun loadCurrentBestLocation(context: Context): Location { fun loadCurrentBestLocation(): Location {
// get preferences val provider: String = sharedPreferences.getString(Keys.PREF_CURRENT_BEST_LOCATION_PROVIDER, LocationManager.NETWORK_PROVIDER) ?: LocationManager.NETWORK_PROVIDER
val settings = PreferenceManager.getDefaultSharedPreferences(context)
val provider: String = settings.getString(Keys.PREF_CURRENT_BEST_LOCATION_PROVIDER, LocationManager.NETWORK_PROVIDER) ?: LocationManager.NETWORK_PROVIDER
// create location // create location
val currentBestLocation: Location = Location(provider) return Location(provider).apply {
// load location attributes // load location attributes
currentBestLocation.latitude = settings.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_LATITUDE, Keys.DEFAULT_LATITUDE) latitude = sharedPreferences.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_LATITUDE, Keys.DEFAULT_LATITUDE)
currentBestLocation.longitude = settings.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_LONGITUDE, Keys.DEFAULT_LONGITUDE) longitude = sharedPreferences.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_LONGITUDE, Keys.DEFAULT_LONGITUDE)
currentBestLocation.accuracy = settings.getFloat(Keys.PREF_CURRENT_BEST_LOCATION_ACCURACY, Keys.DEFAULT_ACCURACY) accuracy = sharedPreferences.getFloat(Keys.PREF_CURRENT_BEST_LOCATION_ACCURACY, Keys.DEFAULT_ACCURACY)
currentBestLocation.altitude = settings.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_ALTITUDE, Keys.DEFAULT_ALTITUDE) altitude = sharedPreferences.getDouble(Keys.PREF_CURRENT_BEST_LOCATION_ALTITUDE, Keys.DEFAULT_ALTITUDE)
currentBestLocation.time = settings.getLong(Keys.PREF_CURRENT_BEST_LOCATION_TIME, Keys.DEFAULT_TIME) time = sharedPreferences.getLong(Keys.PREF_CURRENT_BEST_LOCATION_TIME, Keys.DEFAULT_TIME)
return currentBestLocation }
} }
/* Saves the state of a map */ /* Saves the state of a map */
fun saveCurrentBestLocation(context: Context, currentBestLocation: Location) { fun saveCurrentBestLocation(currentBestLocation: Location) {
// get preferences sharedPreferences.edit {
val settings = PreferenceManager.getDefaultSharedPreferences(context)
settings.edit {
// save location // save location
putDouble(Keys.PREF_CURRENT_BEST_LOCATION_LATITUDE, currentBestLocation.latitude) putDouble(Keys.PREF_CURRENT_BEST_LOCATION_LATITUDE, currentBestLocation.latitude)
putDouble(Keys.PREF_CURRENT_BEST_LOCATION_LONGITUDE, currentBestLocation.longitude) putDouble(Keys.PREF_CURRENT_BEST_LOCATION_LONGITUDE, currentBestLocation.longitude)
@ -161,22 +146,29 @@ object PreferencesHelper {
/* Load currently selected app theme */ /* Load currently selected app theme */
fun loadThemeSelection(context: Context): String { fun loadThemeSelection(): String {
return PreferenceManager.getDefaultSharedPreferences(context).getString(Keys.PREF_THEME_SELECTION, Keys.STATE_THEME_FOLLOW_SYSTEM) ?: Keys.STATE_THEME_FOLLOW_SYSTEM return sharedPreferences.getString(Keys.PREF_THEME_SELECTION, Keys.STATE_THEME_FOLLOW_SYSTEM) ?: Keys.STATE_THEME_FOLLOW_SYSTEM
} }
/* Checks if housekeeping work needs to be done - used usually in DownloadWorker "REQUEST_UPDATE_COLLECTION" */ /* Checks if housekeeping work needs to be done - used usually in DownloadWorker "REQUEST_UPDATE_COLLECTION" */
fun isHouseKeepingNecessary(context: Context): Boolean { fun isHouseKeepingNecessary(): Boolean {
val settings = PreferenceManager.getDefaultSharedPreferences(context) return sharedPreferences.getBoolean(Keys.PREF_ONE_TIME_HOUSEKEEPING_NECESSARY, true)
return settings.getBoolean(Keys.PREF_ONE_TIME_HOUSEKEEPING_NECESSARY, true)
} }
/* Saves state of housekeeping */ /* Saves state of housekeeping */
fun saveHouseKeepingNecessaryState(context: Context, state: Boolean = false) { fun saveHouseKeepingNecessaryState(state: Boolean = false) {
val settings = PreferenceManager.getDefaultSharedPreferences(context) sharedPreferences.edit { putBoolean(Keys.PREF_ONE_TIME_HOUSEKEEPING_NECESSARY, state) }
settings.edit { putBoolean(Keys.PREF_ONE_TIME_HOUSEKEEPING_NECESSARY, state) }
} }
/* Start watching for changes in shared preferences - context must implement OnSharedPreferenceChangeListener */
fun registerPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
sharedPreferences.registerOnSharedPreferenceChangeListener(listener)
}
/* Stop watching for changes in shared preferences - context must implement OnSharedPreferenceChangeListener */
fun unregisterPreferenceChangeListener(listener: SharedPreferences.OnSharedPreferenceChangeListener) {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener)
}
} }

View file

@ -51,7 +51,7 @@ class TracklistAdapter(private val fragment: Fragment) : RecyclerView.Adapter<Re
/* Main class variables */ /* Main class variables */
private val context: Context = fragment.activity as Context private val context: Context = fragment.activity as Context
private lateinit var tracklistListener: TracklistAdapterListener private lateinit var tracklistListener: TracklistAdapterListener
private var useImperial: Boolean = PreferencesHelper.loadUseImperialUnits(context) private var useImperial: Boolean = PreferencesHelper.loadUseImperialUnits()
private var tracklist: Tracklist = Tracklist() private var tracklist: Tracklist = Tracklist()

View file

@ -94,7 +94,7 @@ data class MapFragmentLayoutHolder(private var context: Context, private var mar
mapView.setTileSource(TileSourceFactory.MAPNIK) mapView.setTileSource(TileSourceFactory.MAPNIK)
mapView.setMultiTouchControls(true) mapView.setMultiTouchControls(true)
mapView.zoomController.setVisibility(org.osmdroid.views.CustomZoomButtonsController.Visibility.NEVER) mapView.zoomController.setVisibility(org.osmdroid.views.CustomZoomButtonsController.Visibility.NEVER)
zoomLevel = PreferencesHelper.loadZoomLevel(context) zoomLevel = PreferencesHelper.loadZoomLevel()
controller.setZoom(zoomLevel) controller.setZoom(zoomLevel)
// set dark map tiles, if necessary // set dark map tiles, if necessary
@ -149,8 +149,8 @@ data class MapFragmentLayoutHolder(private var context: Context, private var mar
/* Save current best location and state of map to shared preferences */ /* Save current best location and state of map to shared preferences */
fun saveState(currentBestLocation: Location) { fun saveState(currentBestLocation: Location) {
PreferencesHelper.saveCurrentBestLocation(context, currentBestLocation) PreferencesHelper.saveCurrentBestLocation(currentBestLocation)
PreferencesHelper.saveZoomLevel(context, mapView.zoomLevelDouble) PreferencesHelper.saveZoomLevel(mapView.zoomLevelDouble)
// reset user interaction state // reset user interaction state
userInteraction = false userInteraction = false
} }

View file

@ -137,7 +137,7 @@ data class TrackFragmentLayoutHolder(private var context: Context, private var m
trackManagementViews = rootView.findViewById(R.id.management_icons) trackManagementViews = rootView.findViewById(R.id.management_icons)
// get measurement unit system // get measurement unit system
useImperialUnits = PreferencesHelper.loadUseImperialUnits(context) useImperialUnits = PreferencesHelper.loadUseImperialUnits()
// set dark map tiles, if necessary // set dark map tiles, if necessary
if (AppThemeHelper.isDarkModeOn(context as Activity)) { if (AppThemeHelper.isDarkModeOn(context as Activity)) {