Skip to content

Commit

Permalink
Only monitor flashlight state while app is running
Browse files Browse the repository at this point in the history
  • Loading branch information
kylecorry31 committed Sep 10, 2023
1 parent d9a28f3 commit b321a3d
Show file tree
Hide file tree
Showing 26 changed files with 36 additions and 65 deletions.
11 changes: 11 additions & 0 deletions app/src/main/java/com/kylecorry/trail_sense/main/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import com.kylecorry.trail_sense.shared.sensors.LocationSubsystem
import com.kylecorry.trail_sense.shared.views.ErrorBannerView
import com.kylecorry.trail_sense.tools.battery.infrastructure.commands.PowerSavingModeAlertCommand
import com.kylecorry.trail_sense.tools.clinometer.ui.ClinometerFragment
import com.kylecorry.trail_sense.tools.flashlight.infrastructure.FlashlightSubsystem
import com.kylecorry.trail_sense.tools.flashlight.ui.FragmentToolFlashlight
import com.kylecorry.trail_sense.tools.whitenoise.infrastructure.WhiteNoiseService
import com.kylecorry.trail_sense.volumeactions.ClinometerLockVolumeAction
Expand Down Expand Up @@ -107,6 +108,16 @@ class MainActivity : AndromedaActivity() {
}
}

override fun onResume() {
super.onResume()
FlashlightSubsystem.getInstance(this).startSystemMonitor()
}

override fun onPause() {
super.onPause()
FlashlightSubsystem.getInstance(this).stopSystemMonitor()
}

private fun startApp() {
errorBanner.dismissAll()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,6 @@ import java.time.Duration

class FlashlightPreferenceRepo(context: Context) : PreferenceRepo(context) {

var toggleWithSystem by BooleanPreference(
cache,
getString(R.string.pref_flashlight_toggle_with_system),
false
)

var toggleWithVolumeButtons by BooleanPreference(
cache,
getString(R.string.pref_flashlight_toggle_with_volume),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class FlashlightService : AndromedaService() {
}

override fun onDestroy() {
flashlight.stopSystemMonitor()
topic.unsubscribe(this::onStateChanged)
offTimer.stop()
strategy?.stop()
Expand All @@ -55,6 +56,7 @@ class FlashlightService : AndromedaService() {
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
flashlight.startSystemMonitor()
Notify.send(this, NOTIFICATION_ID, getNotification())
topic.subscribe(this::onStateChanged)
stopAt = cache.getInstant(getString(R.string.pref_flashlight_timeout_instant))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,11 @@ import java.time.Duration
import java.time.Instant
import java.util.*


class FlashlightSubsystem private constructor(private val context: Context) : IFlashlightSubsystem {

private val torchChanged by lazy { TorchStateChangedTopic(context) }
private val cache by lazy { PreferencesSubsystem.getInstance(context).preferences }
private val prefs by lazy { UserPreferences(context) }
private val flashlightSettings by lazy { FlashlightPreferenceRepo(context) }
private var torch: ITorch? = null

private val transitionDuration = Duration.ofSeconds(1)
Expand All @@ -52,21 +50,41 @@ class FlashlightSubsystem private constructor(private val context: Context) : IF

private var brightness: Float = 1f

private val modeLock = Object()
private val torchLock = Object()
private val modeLock = Any()
private val torchLock = Any()
private val systemMonitorLock = Any()

private val scope = CoroutineScope(Dispatchers.Default)

private var systemMonitorCount = 0

init {
_mode.subscribe { true }
scope.launch {
torchChanged.subscribe(this@FlashlightSubsystem::onTorchStateChanged)
brightness = prefs.flashlight.brightness
torch = Torch(context)
isAvailable = Torch.isAvailable(context)
}
}

fun startSystemMonitor(){
synchronized(systemMonitorLock){
systemMonitorCount++
if (systemMonitorCount == 1){
torchChanged.subscribe(this@FlashlightSubsystem::onTorchStateChanged)
}
}
}

fun stopSystemMonitor(){
synchronized(systemMonitorLock){
systemMonitorCount--
if (systemMonitorCount == 0){
torchChanged.unsubscribe(this@FlashlightSubsystem::onTorchStateChanged)
}
}
}

private fun on(newMode: FlashlightMode, bySystem: Boolean = false) = synchronized(modeLock) {
clearTimeout()
if (!bySystem) {
Expand Down Expand Up @@ -139,10 +157,6 @@ class FlashlightSubsystem private constructor(private val context: Context) : IF

private fun onTorchStateChanged(enabled: Boolean): Boolean {
tryOrLog {
if (!flashlightSettings.toggleWithSystem) {
return@tryOrLog
}

synchronized(modeLock) {
if (isTransitioning) {
return@tryOrLog
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-bs/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,6 @@
<string name="pref_cell_signal_refresh_cache_summary">Prisiljava učitavanje najnovijih snaga signala</string>
<string name="pref_cell_signal_refresh_cache_title">Osvježite predmemoriju signala</string>
<string name="pref_navigation_lock_screen_presence_title">Prikaži na zaključanom ekranu tijekom navigacije</string>
<string name="pref_flashlight_toggle_with_system_summary">Prikazuje obavijest kada je svjetiljka uključena izvan Trail Sense-a</string>
<string name="pref_flashlight_toggle_with_system_title">Prebaci sa sistemom</string>
<string name="map_rotate_instructions">Rotirajte dok Sjever nije prema gore usmjeren</string>
<string name="map_perspective_instructions">Zacrtajte kartu</string>
<string name="preview">Pregled</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-cs/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -600,8 +600,6 @@
<string name="move_to">Přesunout do</string>
<string name="moved_to">Přesunuto do %s</string>
<string name="map_rotate_instructions">Otáčejte, dokud sever neukazuje nahoru</string>
<string name="pref_flashlight_toggle_with_system_title">Přepínat se systémem</string>
<string name="pref_flashlight_toggle_with_system_summary">Zobrazí upozornění, když je svítilna zapnutá mimo aplikaci Trail Sense</string>
<string name="humidity_history">Historie vlhkosti - poslední %s</string>
<string name="temperature_history">Historie teploty - poslední %s</string>
<string name="no_groups">Žádné skupiny</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-da/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,6 @@
<string name="cloud_fair_forecast_hours">Kan indikere pænt vejr i de næste %d timer.</string>
<string name="none">Ingen</string>
<string name="pref_show_last_signal_beacon_title">Sidste signalbeacon</string>
<string name="pref_flashlight_toggle_with_system_title">Skift med systemet</string>
<string name="moved_to">Flyttet til %s</string>
<string name="base_temperature">Udgangspunktets temperatur</string>
<string name="clear_cache">Ryd cache</string>
Expand Down Expand Up @@ -792,7 +791,6 @@
<string name="temperature_history">Temperaturhistorik - sidste %s</string>
<string name="pref_nmea_elevation_title">NMEA højdekorrektioner</string>
<string name="convert">Konverter</string>
<string name="pref_flashlight_toggle_with_system_summary">Viser en meddelelse, når lommelygten tændes uden for Trail Sense</string>
<string name="pref_cell_signal_refresh_cache_title">Opdater signalcache</string>
<string name="import_map">Importer kort</string>
<plurals name="number_days">
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -572,8 +572,6 @@
<string name="coordinates_tab">Koordinaten</string>
<string name="distance">Entfernung</string>
<string name="convert">Umrechner</string>
<string name="pref_flashlight_toggle_with_system_summary">Zeigt eine Benachrichtigung an, wenn die Taschenlampe außerhalb von Trail Sense aktiviert wird</string>
<string name="pref_flashlight_toggle_with_system_title">Mit System ändern</string>
<string name="map_rotate_instructions">Rotieren, bis Norden nach oben zeigt</string>
<string name="map_perspective_instructions">Umriss der Karte</string>
<string name="preview">Vorschau</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,6 @@
<string name="import_map">Importar mapa</string>
<string name="quart_format">%s qt</string>
<string name="sort">Clasificar</string>
<string name="pref_flashlight_toggle_with_system_title">Alternar con el sistema</string>
<string name="pref_cell_signal_refresh_cache_summary">Fuerza la carga de las señales más recientes</string>
<string name="location_not_mocked">Usando la ubicación real</string>
<string name="yards_format">%s yd</string>
Expand Down Expand Up @@ -663,7 +662,6 @@
<string name="preview">Vista Previa</string>
<string name="map_perspective_instructions">Delinear el mapa</string>
<string name="map_rotate_instructions">Girar hasta que el norte apunte hacia arriba</string>
<string name="pref_flashlight_toggle_with_system_summary">Muestra una notificación cuando la linterna se enciende fuera de Trail Sense</string>
<string name="pref_navigation_lock_screen_presence_title">Mostrar en la pantalla de bloqueo mientras navega</string>
<string name="pref_cell_signal_refresh_cache_title">Actualizar caché de señales</string>
<string name="pref_backtrack_history_days_title">Historia de retroceso (vuelta atrás)</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-fr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,6 @@
<string name="overridden">Écrasé</string>
<string name="on">Activé</string>
<string name="pref_show_last_signal_beacon_summary">Crée une balise à la dernière position avec signal réseau</string>
<string name="pref_flashlight_toggle_with_system_summary">Afficher une notification quand la lampe torche a été activée en dehors de Trail Sense</string>
<string name="hygiene">Hygiène</string>
<string name="sighting_compass">Boussole</string>
<string name="gps_unavailable_resolution">Activer la position ou changer la source vers Appareil seulement ou Haute précision</string>
Expand All @@ -673,7 +672,6 @@
<string name="odometer">Odomètre</string>
<string name="menu">Menu</string>
<string name="map_rotate_instructions">Tourner jusqu’à ce que le Nord soit au dessus</string>
<string name="pref_flashlight_toggle_with_system_title">Activer au démarrage</string>
<string name="kilograms">Kilogrammes</string>
<string name="weight">Masse</string>
<string name="pref_navigation_lock_screen_presence_title">Afficher sur l’écran de verrouillage lors de la navigation</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-hu/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,6 @@
<string name="pref_barometer_info_summary">A nyomás eltérhet a közeli állomásokétól</string>
<string name="pref_nmea_elevation_title">NMEA magassági eltérések</string>
<string name="distance">Távolság</string>
<string name="pref_flashlight_toggle_with_system_title">Kapcsolás a rendszerrel</string>
<string name="pref_navigation_lock_screen_presence_title">Mutatás a zárolt képernyőn navigálás közben</string>
<string name="pref_cell_signal_refresh_cache_summary">Kényszeríti a legfrissebb térerőadat betöltését</string>
<string name="roll_pitch_yaw">Vízszintes dőlés: %1$s, Függőleges dőlés: %2$s, Elfordulás: %3$s</string>
Expand Down Expand Up @@ -934,7 +933,6 @@
<string name="actual_frequency_disclaimer">A valós frekvencia változó lehet, mivel egyes eszközöknek vannak háttérbeli korlátozásai.</string>
<string name="sleep_timer">Elalvás időzítő</string>
<string name="import_gpx">GPX importálása</string>
<string name="pref_flashlight_toggle_with_system_summary">Értesítést jelenít meg, ha a Trail Sense-n kívül kapcsolódik be a zseblámpa</string>
<string name="sensor_gyroscope">Giroszkóp</string>
<string name="dotted">Pontozott</string>
<string name="backtrack_battery_warning">A rövid intervallumok (kevesebb, mint 15 perc) kimagasló akkuhasználatot okozhatnak</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-in/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,6 @@
<string name="no_groups">Tidak ada grup</string>
<string name="coordinates_tab">Koordinat</string>
<string name="move">Pindah</string>
<string name="pref_flashlight_toggle_with_system_summary">Menampilkan notifikasi ketika senter dinyalakan di luar Trail Sense</string>
<string name="pref_cell_signal_refresh_cache_summary">Memaksa memuat kekuatan sinyal terbaru</string>
<string name="pref_navigation_lock_screen_presence_title">Tampilkan di layar kunci saat menavigasi</string>
<string name="unit_feet">Kaki</string>
Expand Down Expand Up @@ -485,7 +484,6 @@
<string name="battery_usage">%s penggunaan baterai</string>
<string name="whistle_signal_come_here">Kemari</string>
<string name="battery_history">Riwayat baterai - terakhir %s</string>
<string name="pref_flashlight_toggle_with_system_title">Beralih dengan sistem</string>
<string name="actual_frequency_disclaimer">Frekuensi sebenarnya dapat bervariasi karena beberapa perangkat memiliki batasan latar belakang.</string>
<string name="weather_monitor">Pemantau Cuaca</string>
<string name="activity_recognition_permission_denied">Izin aktivitas fisik ditolak, tidak dapat mengaktifkan fitur pedometer. Anda dapat mengaktifkannya di pengaturan.</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-it/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,6 @@
<string name="dawn_type">Alba (%s)</string>
<string name="dusk_type">Crepuscolo (%s)</string>
<string name="no_groups">Nessun gruppo</string>
<string name="pref_flashlight_toggle_with_system_title">Attiva tramite il sistema</string>
<string name="pref_navigation_lock_screen_presence_title">Mostra sulla schermata di blocco durante la navigazione</string>
<string name="imperial_quarts">Quarti imperiali</string>
<string name="volume">Volume</string>
Expand Down Expand Up @@ -741,7 +740,6 @@
<string name="navigation_guide_description">Utilizzando percorsi e segnaposto</string>
<string name="reduce_map_resolution">Riduci la risoluzione della mappa</string>
<string name="humidity_history">Evoluzione dell\'umidità - ultime %s</string>
<string name="pref_flashlight_toggle_with_system_summary">Mostra una notifica al di fuori di Trail Sense quando la torcia è attiva</string>
<string name="move_to">Sposta in</string>
<string name="moved_to">Sposta in %s</string>
<string name="base_elevation">Altitudine di partenza</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-iw/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -753,8 +753,6 @@
<string name="pref_nmea_elevation_summary">שימוש בהיסט NMEA להמרת גובה</string>
<string name="preview">תצוגה מקדימה</string>
<string name="map_rotate_instructions">סובב עד שהצפון יצביע למעלה</string>
<string name="pref_flashlight_toggle_with_system_title">החלף עם המערכת</string>
<string name="pref_flashlight_toggle_with_system_summary">הצגת הודעה כאשר הפנס מופעל מחוץ ל-Trail Sense</string>
<string name="pref_navigation_lock_screen_presence_title">הצג במסך הנעילה בזמן הניווט</string>
<string name="pref_cell_signal_refresh_cache_summary">מאלץ טעינת עוצמת האות העדכנית ביותר</string>
<string name="roll_pitch_yaw">גליל: %1$s, גובה: %2$s, פיתול: %3$s</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-nb-rNO/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,6 @@
<string name="create_map_description">Skriv inn navnet på kartet</string>
<string name="create_map">Opprett kart</string>
<string name="battery_history">Batterihistorikk - siste %s</string>
<string name="pref_flashlight_toggle_with_system_summary">Viser et varsel når lommelykten er slått på utenfor Trail Sense</string>
<string name="import_map">Importer kart</string>
<string name="liter_format">%s l</string>
<string name="milliliter_format">%s ml</string>
Expand Down Expand Up @@ -552,7 +551,6 @@
<string name="beacon_create_beacon">Navigeringsmarkør</string>
<string name="qr_code">QR-kode</string>
<string name="pref_experimental_metal_direction_title">Vis retning til metall</string>
<string name="pref_flashlight_toggle_with_system_title">Slå av/på med system</string>
<string name="map_rotate_instructions">Roter til Nord peker opp</string>
<string name="pref_nmea_elevation_summary">Bruker NMEA-offset for høydeomregning</string>
<string name="pref_nmea_elevation_title">NMEA høyde-offset</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-nl/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -558,8 +558,6 @@
<string name="pref_cell_signal_refresh_cache_summary">Forceert het laden van de nieuwste signaalsterktes</string>
<string name="pref_cell_signal_refresh_cache_title">Signaalcache vernieuwen</string>
<string name="pref_navigation_lock_screen_presence_title">Weergeven op vergrendelscherm tijdens navigeren</string>
<string name="pref_flashlight_toggle_with_system_summary">Geeft een melding weer wanneer de zaklamp is ingeschakeld buiten Trail Sense</string>
<string name="pref_flashlight_toggle_with_system_title">Met systeem in-/uitschakelen</string>
<string name="map_rotate_instructions">Draai totdat het noorden omhoog wijst</string>
<string name="map_perspective_instructions">Maak een overzicht van de kaart</string>
<string name="preview">Voorbeeld</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-pl/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,6 @@
<string name="coordinates_tab">Współrzędne</string>
<string name="no_groups">Brak grup</string>
<string name="preview">Podgląd</string>
<string name="pref_flashlight_toggle_with_system_summary">Wyświetla powiadomienie, gdy latarka zostanie włączona poza programem Trail Sense</string>
<string name="import_map">Importuj mapę</string>
<string name="camera_permission_denied">Odmowa dostępu do aparatu, nie można włączyć funkcji aparatu. Możesz to włączyć w ustawieniach.</string>
<string name="days">Dni</string>
Expand Down Expand Up @@ -591,7 +590,6 @@
<string name="pref_cell_signal_refresh_cache_summary">Wymusza wczytywanie najnowszych danych o mocy sygnału</string>
<string name="pref_cell_signal_refresh_cache_title">Odśwież pamięć podręczną sygnału</string>
<string name="pref_navigation_lock_screen_presence_title">Pokaż na ekranie blokady podczas nawigowania</string>
<string name="pref_flashlight_toggle_with_system_title">Przełącz z systemem</string>
<string name="map_rotate_instructions">Obracaj, aż północ będzie skierowana do góry</string>
<string name="pref_barometer_pressure_smoothing_title">Wygładzanie ciśnienia</string>
<string name="pref_nmea_elevation_summary">Wykorzystuje przesunięcia NMEA do konwersji wysokości</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-pt-rBR/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -532,8 +532,6 @@
<string name="import_map">Importar mapa</string>
<string name="pref_cell_signal_refresh_cache_title">Atualizar o cache de sinal</string>
<string name="pref_navigation_lock_screen_presence_title">Mostrar na tela de bloqueio durante a navegação</string>
<string name="pref_flashlight_toggle_with_system_summary">Exibe uma notificação quando a lanterna for ligada independentemente do Trail Sense</string>
<string name="pref_flashlight_toggle_with_system_title">Alternar com o sistema</string>
<string name="map_rotate_instructions">Girar até que o Norte aponte para cima</string>
<string name="map_perspective_instructions">Contornar o mapa</string>
<string name="preview">Pré-visualização</string>
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/res/values-pt/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -596,8 +596,6 @@
<string name="pref_cell_signal_refresh_cache_summary">Força o carregamento dos últimos níveis de sinal de antena do telemóvel</string>
<string name="pref_cell_signal_refresh_cache_title">Atualizar a cache do sinal de antena do telemóvel</string>
<string name="pref_navigation_lock_screen_presence_title">Mostrar no ecrã de bloqueio durante a navegação</string>
<string name="pref_flashlight_toggle_with_system_summary">Mostra uma notificação quando a lanterna for ligada fora do Trail Sense</string>
<string name="pref_flashlight_toggle_with_system_title">Alternar com o sistema</string>
<string name="map_rotate_instructions">Rodar até que o Norte aponte para cima</string>
<string name="map_perspective_instructions">Endireitar o mapa</string>
<string name="moved_to">Movido para %s</string>
Expand Down
Loading

0 comments on commit b321a3d

Please sign in to comment.