Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

android - AlarmManager set is not firing broadcast

I'm trying to schedule notifications using the AlarmManager but for whatever reason, the onReceive method on my receiver isn't firing.

Here's how I'm scheduling the alarm

        val intent = Intent(this, ReminderReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)

        val cal: Calendar = Calendar.getInstance()
        cal.add(Calendar.SECOND, 5)
        
        val amanager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        amanager.set(AlarmManager.RTC_WAKEUP, cal.timeInMillis, pendingIntent)

and here's the onReceive method

override fun onReceive(context: Context, intent: Intent) {
    Toast.makeText(context,"notification", Toast.LENGTH_SHORT).show()
}

I tried manually sending a broadcast to see if it works and there's no problem there so the issue shouldn't be related to the manifest.

I'm running this on MIUI12 android 10

question from:https://stackoverflow.com/questions/65921630/alarmmanager-set-is-not-firing-broadcast

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I see no issue with your logic if your problem still prevails, try the following as a workaround

val intent = Intent(this, ReminderReceiver::class.java)
        val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)

//        val cal: Calendar = Calendar.getInstance()
//        cal.add(Calendar.SECOND, 5)
        
        val triggerTime = SystemClock.elapsedRealtime() + 5_000 // five seconds from now


        val amanager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
     //   amanager.set(AlarmManager.RTC_WAKEUP, cal.timeInMillis, pendingIntent)
        AlarmManagerCompat.setExactAndAllowWhileIdle(
                    amanager,
                    AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    triggerTime,
                    pendingIntent
                )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...