has*_*ikh 8 android alarm lockscreen alarmmanager android-activity
我试图在屏幕锁定时显示活动。我正在后台运行一个服务,当事件发生时,即使应用程序被锁定,我也想打开一个活动(类似于闹钟应用程序,它唤醒屏幕并显示其活动)。我已按照以下步骤操作,
当调用 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();
}
Run Code Online (Sandbox Code Playgroud)
在我想展示的活动的 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);
}
Run Code Online (Sandbox Code Playgroud)
在清单中添加了我想要显示的活动,
<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"/>
Run Code Online (Sandbox Code Playgroud)
当手机没有锁屏密码时,它可以按预期工作。但当锁屏有密码时就不起作用了。
has*_*ikh 10
最后,我得到了解决方案。
在您想要在锁定屏幕上显示的活动的 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);
Run Code Online (Sandbox Code Playgroud)
显现,
<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"/>
Run Code Online (Sandbox Code Playgroud)
调用活动,
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)
Run Code Online (Sandbox Code Playgroud)