问题描述
我正在尝试在屏幕锁定时显示活动。我在后台运行一个服务,当发生事件时,即使应用程序被锁定,我也想打开一个活动(类似于闹钟应用程序,它会唤醒屏幕并显示其活动)。我已按照以下步骤操作,
当调用 OnReceive() 时,我想在锁定屏幕上打开 Activity。
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();
}
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"/>
当手机没有锁屏密码时,它按预期工作。但是有锁屏密码的时候就不行了。
解决方法
最后,我得到了解决方案。
在要在锁定屏幕上显示的活动的 onCreate 方法中添加以下代码,
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)