@@ -59,6 +59,12 @@ class ScreenOffAccessibilityService : AccessibilityService() {
5959 private var wasNightLightOnBeforeAutoToggle = false
6060 private var isNightLightAutoToggledOff = false
6161 private var lastForegroundPackage: String? = null
62+ private var pendingNLRunnable: Runnable ? = null
63+ private val NL_DEBOUNCE_DELAY = 500L
64+
65+ private val IGNORED_SYSTEM_PACKAGES = listOf (
66+ " android" ,
67+ )
6268
6369 override fun onCreate () {
6470 super .onCreate()
@@ -111,6 +117,23 @@ class ScreenOffAccessibilityService : AccessibilityService() {
111117 }
112118
113119 private fun checkHighlightNightLight (packageName : String ) {
120+ // Cancel any pending NL toggle
121+ pendingNLRunnable?.let { handler.removeCallbacks(it) }
122+
123+ // Skip processing for system packages to avoid transient NL restoration
124+ if (IGNORED_SYSTEM_PACKAGES .contains(packageName)) {
125+ Log .d(" NightLight" , " Ignoring system package $packageName " )
126+ return
127+ }
128+
129+ val runnable = Runnable {
130+ processNightLightChange(packageName)
131+ }
132+ pendingNLRunnable = runnable
133+ handler.postDelayed(runnable, NL_DEBOUNCE_DELAY )
134+ }
135+
136+ private fun processNightLightChange (packageName : String ) {
114137 val prefs = getSharedPreferences(" essentials_prefs" , MODE_PRIVATE )
115138 val isEnabled = prefs.getBoolean(" dynamic_night_light_enabled" , false )
116139 if (! isEnabled) return
@@ -127,22 +150,26 @@ class ScreenOffAccessibilityService : AccessibilityService() {
127150 }
128151
129152 val isAppSelected = selectedApps.find { it.packageName == packageName }?.isEnabled ? : false
130-
153+ val isNLCurrentlyOn = isNightLightEnabled()
154+
131155 if (isAppSelected) {
132- // App is selected, turn off night light if it's currently on
133- if (isNightLightEnabled() ) {
156+ // App is selected. If NL is on , turn it off and record that we did so.
157+ if (isNLCurrentlyOn ) {
134158 Log .d(" NightLight" , " Turning off night light for $packageName " )
135159 wasNightLightOnBeforeAutoToggle = true
136160 isNightLightAutoToggledOff = true
137161 setNightLightEnabled(false )
138162 }
139163 } else {
140- // App is NOT selected, restore night light if we previously turned it off
141- if (isNightLightAutoToggledOff) {
164+ // App is NOT selected.
165+ // Only restore NL if it was auto-toggled off AND it was ON before that.
166+ if (isNightLightAutoToggledOff && wasNightLightOnBeforeAutoToggle) {
142167 Log .d(" NightLight" , " Restoring night light (was turned off for previous app)" )
143168 setNightLightEnabled(true )
144169 isNightLightAutoToggledOff = false
145170 wasNightLightOnBeforeAutoToggle = false
171+ } else if (isNightLightAutoToggledOff) {
172+ isNightLightAutoToggledOff = false
146173 }
147174 }
148175 }
0 commit comments