我有一个待办事项列表应用程序,我想在前台和后台显示通知,我已经实现了代码,并且一切正常,但是当涉及到后台以及应用程序被杀死或设备重启后,通知没有不再显示,我不确定为什么会这样,这就是为什么我在这里寻求帮助的原因,并在此先感谢您提供的任何帮助。
val constraint = Constraints.Builder()
.setRequiresCharging(false)
.setRequiresStorageNotLow(false)
.build()
val oneTimeWorkRequest = OneTimeWorkRequestBuilder<NotificationWorkManager>()
.setConstraints(constraint)
.build()
val workRequest = WorkManager.getInstance(this).enqueue(oneTimeWorkRequest)
var result = workRequest.state.value
when(result){
is SUCCESS ->{
Toast.makeText(this,"Work Manager Success",Toast.LENGTH_SHORT).show()
}
is FAILURE ->{
Toast.makeText(this,"Work Manager Failure",Toast.LENGTH_SHORT).show()
var workUIDD = oneTimeWorkRequest.id
WorkManager.getInstance(this).cancelWorkById(workUIDD)
}
}
class NotificationWorkManager(var context: Context, workerParameters: WorkerParameters) : CoroutineWorker(context,workerParameters) {
private var compat : NotificationManagerCompat? = null
init {
compat = NotificationManagerCompat.from(context)
}
override suspend fun doWork(): Result {
return try {
taskNotification() // this is the function to fire a notification
Result.success()
}catch (throwable : Throwable){
Result.failure()
}
}