如何在广播接收器Android Kotlin中处理多个警报

时间:2018-06-26 10:31:32

标签: android notifications kotlin alarmmanager android-pendingintent

我的运动应用程序允许用户创建多个通知警报,以提示他们进行运动。我正在使用TimePickerDialog设置警报。我正在使用捆绑包将警报的详细信息添加到AlarmReceivers Intent。在StackO上对此进行研究之后,我认为我必须对不同的请求代码使用不同的Pending意图,以产生多个警报。

我的问题是我如何在AlarmReceiver中知道哪个挂起的意图导致了onReceive?我可以使用待定意图的请求代码来确定它是哪一个吗?在意图捆绑包中包含ID并没有帮助,因为它可能同时包含两个警报。

如果可以解释它的工作原理,请先感谢...

class TimePickerFragment : DialogFragment(), TimePickerDialog.OnTimeSetListener {

lateinit var alarmManager: AlarmManager
val intent = Intent(activity, AlarmReceiver::class.java)
val bundle = Bundle()

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

    // use the current time as default values for the picker
    val c = Calendar.getInstance()
    val hour = c.get(Calendar.HOUR_OF_DAY)
    val minute = c.get(Calendar.MINUTE)

    // create a new instance of the TimePicker dialogue and return it
    return TimePickerDialog(getActivity(), this, hour, minute,
            DateFormat.is24HourFormat(getActivity())
            )
override fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {

    val mTag = tag
    if (mTag == "time1") {

        // add alarm to the intent bundle
        bundle.putString("Alarm1", "This is the ${hourOfDay}:${minute} alert")
        intent.putExtras(bundle)
        setAlarm(hourOfDay,minute,intent, 1) //request code 1
    }

   if (mTag == "time2") {
        // add alarm to the intent bundle
        bundle.putString("Alarm2", "This is the ${hourOfDay}:${minute} alert")
        intent.putExtras(bundle)
        setAlarm(hourOfDay,minute,intent, 2) //request code 2
    }
}

fun setAlarm(hourOfDay: Int, minute: Int, intent: Intent, requestCode: Int) {

    alarmManager = activity.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val pendingIntent = PendingIntent.getBroadcast(this.activity, requestCode, intent,PendingIntent.FLAG_UPDATE_CURRENT)

    val calendar = Calendar.getInstance()
    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
    calendar.set(Calendar.MINUTE, minute)
    calendar.set(Calendar.SECOND, 0)
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent)
}

在AlarmReceiver类中:

class AlarmReceiver : BroadcastReceiver() 

{override fun onReceive(context: Context, intent: Intent) {

        val intent = Intent(context, AlarmReceiver::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP

        val pendingIntent = val pendingIntent = PendingIntent.getBroadcast(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT) 
// HOW TO TEST WHICH PENDING INTENT THIS IS?

0 个答案:

没有答案