我正在做一个小任务工,现在遇到了通知问题。我的应用程序将一些任务存储在其内部存储(room db)中。我需要任务处理程序在任务的截止日期结束时通知用户,即使该应用程序已关闭。我已经发出通知,通知将在截止日期结束并且活动仍在打开时弹出。.但是我不知道在关闭我的应用程序时该如何做。这是一些代码:
// NotificationUtil.kt
fun NotificationManager.sendNotification(messageBody: String, applicationContext: Context) {
val contentIntent = Intent(applicationContext, MainActivity::class.java)
val contentPendingIntent = PendingIntent.getActivity(
applicationContext,
NOTIFICATION_ID,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder = NotificationCompat.Builder(
applicationContext,
applicationContext.getString(R.string.task_notification_channel_id)
)
.setSmallIcon(R.drawable.icon)
.setContentTitle(applicationContext.getString(R.string.notification_title))
.setContentText(messageBody)
.setContentIntent(contentPendingIntent)
.setAutoCancel(true)
notify(NOTIFICATION_ID, builder.build())
}
// code which refers to this theme from MainFragment(MainActivity)
listViewModel.tasks.observe(viewLifecycleOwner, Observer {
it.forEach {
if (it.date.isBefore(LocalDate.now()) && it.date != LocalDate.MIN && it.stage == 0) {
val notificationManager = ContextCompat.getSystemService(
application,
NotificationManager::class.java
) as NotificationManager
notificationManager.sendNotification(application
.getString(R.string.you_missed_the_deadline), application)
}
}
})
fun createChannel(channelId: String, channelName: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_DEFAULT).apply {
setShowBadge(false)
}
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.BLUE
notificationChannel.enableVibration(true)
notificationChannel.description =
getString(R.string.task_notification_channel_description)
val notificationManager = requireActivity().getSystemService(
NotificationManager::class.java)
notificationManager.createNotificationChannel(notificationChannel)
}
}
createChannel(
getString(R.string.task_notification_channel_id),
getString(R.string.task_notification_channel_name)
)
// Entity, if needed
@Entity(tableName = "tasks_table")
@TypeConverters(Converters::class)
data class Task(
@PrimaryKey(autoGenerate = true)
var taskId: Long,
@ColumnInfo(name = "task_title")
var title: String,
@ColumnInfo(name = "task_details")
var details: String,
@ColumnInfo(name = "task_date")
var date: LocalDate = LocalDate.MIN,
@ColumnInfo(name = "task_stage")
var stage: Int = 0
)
提前谢谢!