|
| 1 | +package app.grapheneos.camera |
| 2 | + |
| 3 | +import android.app.Activity |
| 4 | +import android.content.BroadcastReceiver |
| 5 | +import android.content.Context |
| 6 | +import android.content.Intent |
| 7 | +import android.content.IntentFilter |
| 8 | +import android.os.Handler |
| 9 | +import android.os.Looper |
| 10 | +import androidx.core.app.ActivityCompat |
| 11 | + |
| 12 | +// Finishes the passed [activity] and the ones present below it in the stack if the screen |
| 13 | +// turns off and the user is inactive for [WAITING_TIME_IN_MS] milliseconds |
| 14 | +class AutoFinishOnSleep(val activity: Activity) { |
| 15 | + |
| 16 | + companion object { |
| 17 | + private const val TAG = "AutoFinishOnSleep" |
| 18 | + private const val WAITING_TIME_IN_MS = 1500L |
| 19 | + |
| 20 | + private val intentFilter = IntentFilter().apply { |
| 21 | + addAction(Intent.ACTION_SCREEN_ON) |
| 22 | + addAction(Intent.ACTION_SCREEN_OFF) |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + private val handler = Handler(Looper.getMainLooper()) |
| 27 | + |
| 28 | + private val runnable = Runnable { |
| 29 | + ActivityCompat.finishAffinity(activity) |
| 30 | + } |
| 31 | + |
| 32 | + private val receiver = object: BroadcastReceiver() { |
| 33 | + override fun onReceive(context: Context?, intent: Intent?) { |
| 34 | + when(intent?.action) { |
| 35 | + Intent.ACTION_SCREEN_OFF -> { |
| 36 | + handler.postDelayed(runnable, WAITING_TIME_IN_MS) |
| 37 | + } |
| 38 | + |
| 39 | + Intent.ACTION_SCREEN_ON -> { |
| 40 | + handler.removeCallbacks(runnable) |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + fun start() { |
| 47 | + activity.registerReceiver(receiver, intentFilter) |
| 48 | + } |
| 49 | + |
| 50 | + fun stop() { |
| 51 | + activity.unregisterReceiver(receiver) |
| 52 | + } |
| 53 | +} |
0 commit comments