息屏后亮屏并显示Activity在锁屏页面之上
1. 加权限
<uses-permission android:name="android.permission.WAKE_LOCK" />
2. 加代码
- SDK 大于等于27
override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)// 需要该Activiy在锁屏状态下显示时,显示在锁屏之上,不加在这里第一次显示不起作用if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {setShowWhenLocked(true)}setContentView(R.layout.activity_main)}
- 亮屏
val powerManager = p0?.getSystemService(Context.POWER_SERVICE) as PowerManagervar isScreenOn = when {Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH -> {powerManager.isInteractive}else -> {powerManager.isScreenOn}}if (!isScreenOn) {val wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK,"wakeupScreen") as PowerManager.WakeLockwakeLock.acquire(1000)wakeLock.release()}
- 解锁并显示activity的代码
val km = p0.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager// 判断是否锁屏val isLocked = km.isKeyguardLocked// 判断是否需要密码,图形,pin解锁val isLockedWithPassword = km.isKeyguardSecureval activity = p0 as Activityif (isLocked) {Log.i(TAG, "it is locked")if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {activity.setShowWhenLocked(true)Log.i(TAG, "setShowWhenLocked")if (isLockedWithPassword.not()) {km.requestDismissKeyguard(activity, null)Log.i(TAG, "requestDismissKeyguard")}} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O) {if (isLockedWithPassword) {//WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,表示可以显示在锁屏之上 activity.window?.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)Log.i(TAG, "addFlags: FLAG_SHOW_WHEN_LOCKED")} else {if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {activity.window?.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)km.requestDismissKeyguard(activity, null)Log.i(TAG, "requestDismissKeyguard")} else {// WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD 表示锁屏设置的是上滑解锁,它可以帮助我们上滑并显示activityactivity.window?.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD)Log.i(TAG, "addFlags: FLAG_DISMISS_KEYGUARD")}}}
视频DEMO
https://download.csdn.net/download/zcpHappy/85837139