omnivore-app / omnivore

Omnivore is a complete, open source read-it-later solution for people who like reading.
https://omnivore.app
GNU Affero General Public License v3.0
13.73k stars 917 forks source link

[Feature request] Keep screen on when reading an article in android app #2486

Open thelazyoxymoron opened 1 year ago

thelazyoxymoron commented 1 year ago

When an article is opened, it should trump system settings for screen timeout and keep the screen on.

Makes for a nice reading experience :)

jacksonh commented 1 year ago

oh nice, looks like we need to do roughly this:

import android.content.Context
import android.os.Build
import android.os.PowerManager
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity

class ReaderActivity : AppCompatActivity() {
    private lateinit var wakeLock: PowerManager.WakeLock

    override fun onResume() {
        super.onResume()
        keepScreenOn()
    }

    override fun onPause() {
        super.onPause()
        releaseWakeLock()
    }

    private fun keepScreenOn() {
        val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
        wakeLock = powerManager.newWakeLock(
            PowerManager.SCREEN_BRIGHT_WAKE_LOCK or
            PowerManager.ACQUIRE_CAUSES_WAKEUP or
            PowerManager.ON_AFTER_RELEASE, "MyWakeLock"
        )

        // For devices running Android 6.0 (Marshmallow) and above, use the FLAG_KEEP_SCREEN_ON flag
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        } else {
            wakeLock.acquire()
        }
    }

    private fun releaseWakeLock() {
        if (wakeLock.isHeld) {
            wakeLock.release()
        }
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }
}