【问题标题】:Kotlin AlarmManager and BroadcastReceiver not workingKotlin AlarmManager 和 BroadcastReceiver 不起作用
【发布时间】:2017-11-15 17:14:03
【问题描述】:

我正在尝试使用 AlarmManager 设置警报,但我的 BroadcastReceiver 从未被调用。这是我的sn-p。

    val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            //Never gets hit
        }
    }
    context.registerReceiver(receiver, IntentFilter(LOCAL_NOTIFICATION))

    val intent = Intent()
    intent.action = LOCAL_NOTIFICATION

    val alarmManager = context.getSystemService(ALARM_SERVICE) as? AlarmManager
    val pendingIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    val calendar = Calendar.getInstance()

    calendar.add(Calendar.SECOND, 10)

    alarmManager?.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

我尝试在 AndroidManifest.xml 中注册广播接收器,但似乎没有任何效果。

【问题讨论】:

    标签: android broadcastreceiver kotlin alarmmanager


    【解决方案1】:

    我刚刚注意到我在PendingIntent 上调用getService() 而不是getBroadcast()

    改了之后就完美了!

    【讨论】:

      【解决方案2】:

      除了首选答案之外,我还在它起作用之前设置了意图的类。请参见下面的示例:

      val intent = Intent()
      intent.action = LOCAL_NOTIFICATION
      intent.setClass(context, MyBroadCastReceiver::class.java) //this line
      

      在将意图传递给 pendintIntent 之前。 希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-12
        • 1970-01-01
        相关资源
        最近更新 更多