简体   繁体   English

AlarmManager 设置未触发广播

[英]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.我正在尝试使用 AlarmManager 安排通知,但无论出于何种原因,我的接收器上的 onReceive 方法都没有触发。

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这是 onReceive 方法

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我在 MIUI12 android 10 上运行这个

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
                )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM