Android Galaxy S4 — Activity that is visible over lock screen

前端 未结 5 1020
一整个雨季
一整个雨季 2020-12-09 05:08

A few years ago, I wrote an alarm app that worked on Android 2, and I\'m now trying to upgrade it to work on Android 4. Specifically, on the Samsung Galaxy S4.

On A

5条回答
  •  天命终不由人
    2020-12-09 05:43

    In Kotlin,

    For Api level 28 or less, you can simply add below method in your activity that needs to be opened:

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        toBeShownOnLockScreen()
    }
    
    private fun toBeShownOnLockScreen() {
        window.addFlags(
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setTurnScreenOn(true)
            setShowWhenLocked(true)
        } else {
            window.addFlags(
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                        or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            )
        }
    }
    

    And to make it work on Android Pie and above, in additional to above step, we need to set in AndroidManifest as well:

    
    

    I have tested this code from Api level 21 to 29, and works like charm!

提交回复
热议问题