I am working on an alarm clock where the alarm is received by a receiver that starts a service. In that service, I start a ForegroundService
. Then a Handler with a 60s delay start the alarm sound.
The problem is, that sometimes the notification and the sound start 1 minute too late.
The receiver and the service start at the right time, but the notification and sound don't. I already tried to replace the Handler, but it didn't work.
AlarmService:
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notificationChannel : NotificationChannel
val notificationBuilder : Notification.Builder
val channelId = "alarm"
val description = resources.getString(R.string.alarms)
val notificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val alarmScreen = Intent(this, AlarmScreen::class.java)
alarmScreen.putExtra("alarmNumber", alarmNumber)
val alarmScreenPendingIntent = PendingIntent.getActivity(this, 5000, alarmScreen, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH)
notificationChannel.enableVibration(false)
notificationChannel.setSound(null, null)
notificationManager.createNotificationChannel(notificationChannel)
notificationBuilder = Notification.Builder(this, channelId)
.setContentTitle(resources.getString(R.string.alarm))
.setContentText(resources.getString(R.string.clickToOpenAlarmScreen))
.setSmallIcon(R.drawable.logo_alarm)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.logo_alarm))
.setContentIntent(alarmScreenPendingIntent)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setFullScreenIntent(alarmScreenPendingIntent, true)}
else{
notificationBuilder = Notification.Builder(this)
.setContentTitle(resources.getString(R.string.alarms))
.setContentText(resources.getString(R.string.clickToOpenAlarmScreen))
.setSmallIcon(R.drawable.logo_alarm)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.logo_alarm))
.setContentIntent(alarmScreenPendingIntent)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setFullScreenIntent(alarmScreenPendingIntent, true)}
startForeground(1000, notificationBuilder.build())
fun Activity.turnScreenOnAndKeyguardOff() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true)
setTurnScreenOn(true)
} else {
window.addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
or WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
)
}
with(getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
requestDismissKeyguard(this@turnScreenOnAndKeyguardOff, null)
}}}
Handler(Looper.getMainLooper()).postDelayed({
AlarmSound.playAlarm(applicationContext) //Starts the alarm sound object
}, 60000)
return START_STICKY
}
CodePudding user response: