Activity 在打瞌睡模式下启动时保持黑色

Activity Remains BLACK when launching under Doze Mode

所以我有一个警报 activity,它从服务启动,并且 在打瞌睡模式 时,activity 仍然存在黑色 直到我把它关掉再打开。

现在,虽然屏幕是黑色的,但视图是有响应的(如果我触摸它们,它们就会工作)

如果我尝试截取屏幕截图,我会突然看到 activity,并且 如果我关闭屏幕然后再次打开,一切都会按预期工作

怪异视频:

Responsive black screen

Turn off, and on again

Trying to take a screenshot

我基本上就是这样启动 activity:

val builder = NotificationCompat.Builder(context, NotificationChannels.CHANNEL_ALARM_SERVICE)
...
// set intent
val alarmIntent = Intent(context, AlarmActivity::class.java)
alarmIntent.putExtra(IntentExtras.KEY_ID, alarm.id)
builder.setFullScreenIntent(PendingIntent.getActivity(context, RequestCodes.REQUEST_CODE_ALARM_ACTIVITY, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT), true)
...
startForeground(...)

这就是我在 Activity 的 onCreate 方法中解锁屏幕的方式

public class ScreenUnlockerUtil {

public static void unlockScreen(BaseActivity activity) {

    activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
            | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
            | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
        // in addition to flags
        activity.setShowWhenLocked(true);
        activity.setTurnScreenOn(true);
        return;
    }


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        KeyguardManager keyguardManager = (KeyguardManager) activity.getSystemService(KEYGUARD_SERVICE);
        if (keyguardManager != null) {
            keyguardManager.requestDismissKeyguard(activity, new KeyguardManager.KeyguardDismissCallback() {
                @Override
                public void onDismissError() {
                    super.onDismissError();
                    Timber.e("Keyguard Dismiss Error");
                }

                @Override
                public void onDismissSucceeded() {
                    super.onDismissSucceeded();
                    Timber.d("Keyguard Dismiss Success");
                }

                @Override
                public void onDismissCancelled() {
                    super.onDismissCancelled();
                    Timber.w("Keyguard Dismiss Cancelled");
                }
            });
        }
        return;
    }


}

我设法用

重现了这个问题
adb shell dumpsys deviceidle force-idle

我自然无法 post 所有代码,但如果您有任何需要,请告诉我。

谢谢!

从您的 if 语句中删除 return

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
    // in addition to flags
    activity.setShowWhenLocked(true);
    activity.setTurnScreenOn(true);
    //return;
}