首页 > 解决方案 > 在android中发送重复通知

问题描述

我试图在特定日期(例如,星期日、星期一等)和时间向用户发送本地通知,所以我所做的是我创建了一个广播接收器类并在那里设置通知消息,然后我在活动类中创建请求,但它似乎已损坏,它有时会在所选时间之前工作,如果我将时间设置为上午 9:00,它会在晚上 9:00 发送通知,同时我检查我是否使用 24 格式时间选择和最后一个问题是它不考虑 Calender.DAY_OF_WEEK 这是我的代码

我的广播接收器类

class ReminderBroadcast : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val prefs = context.getSharedPreferences("generalPrefs", Context.MODE_PRIVATE)
        val courseName = prefs.getString("courseName", "")
        val builder = NotificationCompat.Builder(context, "notifyLecture")
            .setSmallIcon(R.drawable.club_icon)
            .setColor(getColor(context, R.color.colorPrimary))
            .setContentTitle("your $courseName will begin in 5 minutes")
            .setContentText("hey user your $courseName will begin in 5 minutes")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)

        val notificationManager = NotificationManagerCompat.from(context)

        notificationManager.notify(1, builder.build())
    }
}

我的通知创建功能

private fun createNotification(hours: Int, minutes: Int, day: Int, subjectName: String) {
    val alarmIntent = Intent(this, ReminderBroadcast::class.java).let { intent ->
        PendingIntent.getBroadcast(this, 0, intent, 0)
    }
    val prefs = getSharedPreferences("generalPrefs", Context.MODE_PRIVATE)
    val editor = prefs.edit()
    editor.putString("courseName", subjectName)
    editor.apply()
    val calendar: Calendar = Calendar.getInstance().apply {
        timeInMillis = System.currentTimeMillis()
        set(Calendar.DAY_OF_WEEK, day)
        set(Calendar.HOUR_OF_DAY, hours)
        set(Calendar.MINUTE, minutes)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }
    val alarmManager: AlarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
    alarmManager.setRepeating(
        AlarmManager.RTC_WAKEUP,
        calendar.timeInMillis,
        1000 * 60 * 60 * 24 * 7,
        alarmIntent
    )
}

所以我的目标是为选定的日期和时间(由用户)创建一个通知,然后每周重复一次。我在这里做错了什么

标签: androidkotlinbroadcastreceiver

解决方案


推荐阅读