我正在尝试用闹钟开始一项活动。 PendingIntent启动接收器,接收器启动活动。我目前的问题是活动在后台开始,听不到警报声。对于Oreo和更新的设备,旧的SO问题中的大多数标志都已弃用。有没有人有一个很好的方法如何处理这个?
先感谢您
报警创建:
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中
<activity
android:name=".AlarmActivity"
android:showOnLockScreen="true"
android:turnScreenOn="true"/>
以下检查也应该在setContentView()之后。因为在您添加标志时,没有可以使用它们的视图。
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)
}