如何在Android中每周设置通知:经常性通知,样式选项等。
#kotlin #android #mobile #notifications

作为开发人员,您知道用户参与对于您的应用程序的成功至关重要。但是,您如何让用户回来?一种简单的解决方案是实施每周通知,以提醒他们定期使用您的应用程序。在这篇博客文章中,我将介绍使用Android的AlarmManager和日历类为您的应用程序设置每周通知的过程。无论您是构建生产力应用程序,健身追踪器还是冥想指南,这些通知都可以帮助您的用户保持正轨并实现目标。

Screenshot of notification
这是您设置预定的每周通知(每个星期一1213pm)时发生的情况。

这篇文章将涵盖以下

  • 创建即时通知
  • 创建每周通知(如果用户不重新输入应用程序,请勿重复)
  • 创建经常性通知(即使用户不重新输入应用程序,重复也可以重复)
  • 造型通知

创建即时通知

,对于每条通知,我们需要设置以下内容通知管理器,频道(ID,名称和重要性),通知构建器(您在其中添加了通知详细信息),最后在管理器上与构建器一起在经理上拨打.notify(),以显示通知。

    fun triggerImmediateNotification(context: Context) {
        val notificationManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        // create notification channel
        val channelId = "my_channel_id"
        val channelName = "My Channel"
        val importance = NotificationManager.IMPORTANCE_HIGH
        val channel = NotificationChannel(channelId, channelName, importance)
        notificationManager.createNotificationChannel(channel)

        // build notification (style it here)
        val notificationBuilder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_notifications)
            .setContentTitle("My Notification Title")
            .setContentText("This is an immediate notification.")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)

        // set it to notify immediately
        val notificationId = 1
        notificationManager.notify(notificationId, notificationBuilder.build())
    }

创建预定的每周通知

现在我们都在这里。我们如何设置每周通知?我们将转向以下代码的主要目的,这意味着该代码每次用户输入应用程序

时都会运行。

安排通知

您想显示通知的星期几和时间?我们不必将其存储在偏好中,就好像它在同一周内始终设置为本周星期日。

// sunday 12pm in the afternoon
val calendar = Calendar.getInstance()
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY) // Sunday
calendar.set(Calendar.HOUR_OF_DAY, 12) // 12pm
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)

然后,我们需要检查计划的时间是否过去了。当用户收到通知后再次打开应用程序时,会发生这种情况,我们将希望将日历日重置为下一周。

// Check if the scheduled time is in the past, if it is, add a week
if (calendar.timeInMillis < System.currentTimeMillis()) {
    calendar.add(Calendar.WEEK_OF_YEAR, 1)
}

接下来,我们将设置一个意图,该意图将发送到NotificationReciever类,我们将在以后进行

val notificationIntent = Intent(this, NotificationReceiver::class.java)
notificationIntent.putExtra("notificationId", 1)
notificationIntent.putExtra("message", "Time to kick back, relax, and focus on your well-being. Don't forget to use our app to track your progress and goals. Let's make this week amazing together!")
notificationIntent.putExtra("title", "Self-Care Sunday!")
val pendingIntent = PendingIntent.getBroadcast(
    applicationContext,
    0,
    notificationIntent,
    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)

我们还需要设置警报管理器以在时间到来时推动意图。

val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent) // will not repeat until user enters app again

响应警报和通知:NotificationReciever类

现在让我们处理我们最初计划的意图

class NotificationReceiver : BroadcastReceiver() {
    // creates notification when it is time

    override fun onReceive(context: Context, intent: Intent) {
        val notificationId = intent.getIntExtra("notificationId", 0)
        val message = intent.getStringExtra("message")
        val title = intent.getStringExtra("title")

        val notificationManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val notificationBuilder = NotificationCompat.Builder(context, "my_channel_id")
            .setSmallIcon(R.drawable.ic_notifications)
            .setContentTitle(title)
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true) // styling the notification

        notificationManager.notify(notificationId, notificationBuilder.build())
    }
}

创建经常性通知

我们将首先创建一个函数以根据日历安排通知。

    private fun scheduleRecurringNotification(calendar: Calendar, title: Int, message: Int){
        // set recurring every 2 days
        val notificationIntent = Intent(this, NotificationReceiver::class.java)
        notificationIntent.putExtra("notificationId", 2)
        notificationIntent.putExtra("title", applicationContext.getString(title))
        notificationIntent.putExtra("message", applicationContext.getString(message))
        val pendingIntent = PendingIntent.getBroadcast(
            applicationContext,
            0,
            notificationIntent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )

        val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
        val interval = 2 * 24 * 60 * 60 * 1000 // interval in milliseconds
//        val interval = 60000 // for every minute during testing

        alarmManager.
        setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            interval.toLong(),
            pendingIntent
        ) // repeating alarm (repeats every 2 days based on interval
    }

然后,我们将使用该函数来安排像此这样的通知

    fun scheduleEvery2DayNotification() {
        // will be reset when user uses the app, (if daily user, wont see notification)
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 21)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        scheduleRecurringNotification(calendar, R.string.day2_notification_title , R.string.day2_notification_text)
    }

样式通知

正如我们前面提到的,我们还将使用通知构建器对通知进行样式。

我将介绍一些常见的自定义。现在让我们尝试做这样的通知。

Parts of a Notification

val notificationBuilder = NotificationCompat.Builder(context, "my_channel_id")
    .setSmallIcon(R.drawable.icon) // small icon
    .setContentTitle(title) // content title
    .setContentText(message) // content text (this shows when the notification is not expanded)
    .setPriority(NotificationCompat.PRIORITY_HIGH)
    .setAutoCancel(true)
    .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.icon)) // you can also set a big icon on the right like how Gmail does it
    .setStyle(NotificationCompat.BigTextStyle()
        .bigText(message)) // this is the text shown when the notification is expanded
    .addAction(R.drawable.ic_notifications, "Write", pendingIntent) // adding actions (buttons)
    .setDefaults(NotificationCompat.DEFAULT_ALL)

更多关于造型通知的信息:https://developer.android.com/develop/ui/views/notifications/expanded


感谢您的阅读,发表评论,让我知道您的想法!希望有助于在Android中创建通知! :)

社交

Github LinkedIn Portfolio