在Android中设置密码时如何在锁定屏幕上显示活动

我试图在屏幕锁定时显示活动。我在后台运行服务,当事件发生时,即使应用程序被锁定,我也想打开一个活动(类似于警报应用程序,它唤醒屏幕并显示其活动)。我已按照以下步骤操作,

调用 OnReceive() 时,我想在锁定屏幕上打开活动。

public void OnReceive() {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "myalarmapp:alarm.");
            wl.acquire(5000);

            Intent startAlarmActivity = new Intent(MainScreen.this, AcceptScreen.class);

            startActivity(startAlarmActivity);

            wl.release();
        }

在我要显示的活动的 onCreate 方法中添加了以下代码,

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {

        setShowWhenLocked(true);
        setTurnScreenOn(true);
        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        keyguardManager.requestDismissKeyguard(this, null);
    }
    else {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

在清单中为我要显示的活动添加了这个,

<activity
        android:name=".v2.ui.orderaccept.AcceptScreen"
        android:exported="true"
        android:label="@string/title_activity_accept_screen"
        android:theme="@style/AppTheme.NoActionBar"
        android:showOnLockScreen="true"
        android:screenOrientation="sensorPortrait"/>

当手机没有锁屏密码时,它按预期工作。但是当有锁屏密码时它不起作用。

stack overflow How To Show Activity On Lock Screen When Password Is Set In Android
原文答案

答案:

作者头像

最后,我得到了解决方案。

在Activiti

final Window win = getWindow();
    win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);

显现,

<activity
        android:name=".v2.ui.orderaccept.AcceptScreen"
        android:exported="true"
        android:label="@string/title_activity_accept_screen"
        android:theme="@style/AppTheme.NoActionBar"
        android:launchMode="singleInstance"/>

致电活动,

val intent = Intent(context, targetclass)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        startActivity(intent)