即使关闭屏幕也可以开始活动

编程入门 行业动态 更新时间:2024-10-28 20:21:27
本文介绍了即使关闭屏幕也可以开始活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试通过警报启动活动. PendingIntent启动接收器,接收器启动活动.我当前的问题是活动从后台开始,无法听到警报声. 较旧的SO问题中的大多数标志对于Oreo和较新的设备均已弃用.有谁有很好的方法来解决这个问题?

I'm trying to start an activity with an alarm. The PendingIntent starts a receiver and the receiver starts the activity. My current issue is that the activity starts in the background and it's impossible to hear the alarm sound. Most of the flags from older SO questions are deprecated for Oreo and newer devices. Does anyone have a good approach how to handle this?

提前谢谢

警报创建:

alarmManager.setExact(AlarmManager.RTC_WAKEUP, intervalFinished, pendingIntent)

接收器

class OnAlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val intent = Intent(context, AlarmActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } }

活动:

private var wake: PowerManager.WakeLock? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager wake = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP, "App:wakeuptag") wake?.acquire(10*60*1000L /*10 minutes*/) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { setShowWhenLocked(true) setTurnScreenOn(true) } else { window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) } setContentView(R.layout.activity_layout) } override fun onPause() { super.onPause() if(wake != null && wake!!.isHeld){ wake!!.release() } }

推荐答案

您应该在AndroidManifest.xml中添加

You should have in your AndroidManifest.xml

<activity android:name=".AlarmActivity" android:showOnLockScreen="true" android:turnScreenOn="true"/>

以下检查也应在 setContentView()之后.由于在您添加标志时,没有可以使用它们的视图.

Also the following check should be after the setContentView(). Since at the time you adding the flags there is not view that can make use of them.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { setShowWhenLocked(true) setTurnScreenOn(true) } else { window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) }

更多推荐

即使关闭屏幕也可以开始活动

本文发布于:2023-11-27 01:15:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635960.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:屏幕

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!