简体   繁体   中英

open activity above lockscreen

I've tried opening an Activity on the lock screen in Android Pie but I could not. I added the showWhenLocked and turnScreenOn on the Android Manifest and on the proper activity and permissions I searched for but could not make the activity open on the default lock screen on the phone. Some help?

MainActivity

if (Build.VERSION.SDK_INT >= 27) {
        setShowWhenLocked(true);
        setTurnScreenOn(true);
    } else {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    }

Android Manifest

android:showWhenLocked="true"
android:turnScreenOn="true"
android:showOnLockScreen="true"
android:excludeFromRecents="true"

Here is my working method call it from onCreate() before setContentView() of activity

Also set below flag for your activity in AndroidManifest file.

android:showOnLockScreen="true"

/** * Allow calling screen to display over lock screen */

private fun allowOnLockScreen() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
        setShowWhenLocked(true)
        setTurnScreenOn(true)
        val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
        keyguardManager.requestDismissKeyguard(this, null)
    } else {
        this.window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON)
    }
}

Just override the following method in your activity which you want to open on the lock screen.

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}

And add the following tag to your activity in Manifest.

android:excludeFromRecents="true"

Something like this should work:

PowerManager.WakeLock cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XXX:CPU_WAKE_LOCK");
cpuWakelock.acquire();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM