package us.beckmeyer.autobrightnessdelay import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.IBinder import android.provider.Settings import androidx.core.app.NotificationChannelCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch class AutoBrightnessDelayService : Service() { companion object { private const val CHANNEL_ID = "guard_channel" private const val NOTIFICATION_ID = 42 private val SCREEN_ON_DELAY = 500.milliseconds } private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) private var pendingJob: Job? = null private val screenReceiver = object : BroadcastReceiver() { override fun onReceive(ctx: Context, intent: Intent) { pendingJob?.cancel() // cancel any "mid-flight" task when (intent.action) { Intent.ACTION_SCREEN_OFF -> { disableAutoBrightness() } Intent.ACTION_SCREEN_ON, Intent.ACTION_USER_PRESENT -> { pendingJob = scope.launch { delay(SCREEN_ON_DELAY) enableAutoBrightness() pendingJob = null } } } } } override fun onCreate() { super.onCreate() createNotificationChannel() startForeground( NOTIFICATION_ID, NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("AutoBrightnessDelay running") .setSmallIcon(R.drawable.brightness_auto) .setOngoing(true) .build(), ) IntentFilter().apply { addAction(Intent.ACTION_SCREEN_OFF) addAction(Intent.ACTION_SCREEN_ON) addAction(Intent.ACTION_USER_PRESENT) registerReceiver(screenReceiver, this, RECEIVER_NOT_EXPORTED) } } override fun onDestroy() { pendingJob?.cancel() scope.cancel() unregisterReceiver(screenReceiver) super.onDestroy() } override fun onBind(intent: Intent?): IBinder? = null private fun disableAutoBrightness() { if (!Settings.System.canWrite(this)) return Settings.System.putInt( contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, ) } private fun enableAutoBrightness() { if (!Settings.System.canWrite(this)) return Settings.System.putInt( contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC, ) } private fun createNotificationChannel() { NotificationManagerCompat.from(this) .createNotificationChannel( NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManagerCompat.IMPORTANCE_MIN) .setName("AutoBrightnessDelay Service") .setSound(null, null) .build() ) } }