Prefs.kt
| 1 | package org.opentracker |
| 2 | |
| 3 | import android.content.Context |
| 4 | import android.content.SharedPreferences |
| 5 | import kotlin.properties.ReadWriteProperty |
| 6 | import kotlin.reflect.KProperty |
| 7 | |
| 8 | /** Everything the app keeps. The service reads it on every start, because a restarted sticky service gets no Intent. */ |
| 9 | class Prefs(context: Context) { |
| 10 | val raw: SharedPreferences = context.getSharedPreferences("ot", Context.MODE_PRIVATE) |
| 11 | |
| 12 | // The property name is the stored key. Renaming a property loses the setting on existing installs. |
| 13 | var url by string() |
| 14 | var token by string() |
| 15 | var tracking by boolean() |
| 16 | |
| 17 | /** The secret behind a pairing challenge, until the browser returns with a code. */ |
| 18 | var pairVerifier by string() |
| 19 | |
| 20 | /** A [Mode] name. */ |
| 21 | var mode by string() |
| 22 | var lastUploadMs by long() |
| 23 | var queued by long() |
| 24 | var error by string() |
| 25 | |
| 26 | /** The mode in the user's language. */ |
| 27 | fun modeLabel(context: Context): String? = when (mode) { |
| 28 | Mode.VEHICLE.name -> context.getString(R.string.mode_vehicle) |
| 29 | Mode.WALK.name -> context.getString(R.string.mode_walk) |
| 30 | Mode.DWELL.name -> context.getString(R.string.mode_dwell) |
| 31 | Mode.STATIONARY.name -> context.getString(R.string.mode_stationary) |
| 32 | else -> null |
| 33 | } |
| 34 | |
| 35 | fun asked(step: String): Boolean = raw.getBoolean("asked $step", false) |
| 36 | |
| 37 | fun markAsked(step: String) = raw.edit().putBoolean("asked $step", true).apply() |
| 38 | |
| 39 | private fun string() = pref({ getString(it, null) }, { k, v: String? -> putString(k, v) }) |
| 40 | |
| 41 | private fun long() = pref({ getLong(it, 0) }, { k, v: Long -> putLong(k, v) }) |
| 42 | |
| 43 | private fun boolean() = pref({ getBoolean(it, false) }, { k, v: Boolean -> putBoolean(k, v) }) |
| 44 | |
| 45 | private fun <T> pref(get: SharedPreferences.(String) -> T, put: SharedPreferences.Editor.(String, T) -> Unit) = |
| 46 | object : ReadWriteProperty<Any?, T> { |
| 47 | override fun getValue(thisRef: Any?, property: KProperty<*>): T = raw.get(property.name) |
| 48 | |
| 49 | override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = |
| 50 | raw.edit().apply { put(property.name, value) }.apply() |
| 51 | } |
| 52 | } |
| 53 |