我想安排一个工作人员在设备插入并连接到互联网时显示通知 [英] I want to schedule a worker to show a notification when the device is plugged in and connected to the internet

查看:62
本文介绍了我想安排一个工作人员在设备插入并连接到互联网时显示通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我认为标题是不言自明的...我必须使用WorkManager api来安排一个通知,该通知将在设备每次连接到互联网并且正在充电(插入)时显示.我设法创建了一个工作程序并使其显示通知,但是这里的问题是它只显示了一次通知.之后,即使我断开/重新连接到wifi并拔下/插入电缆,它也不会显示通知.

Alright, I think the title is pretty self-explanatory...I have to use the WorkManager api to schedule a notification that will be displayed every time the device is connected to the internet and is charging(plugged-in). I managed to create a worker and make it display the notification, but the issue here is that it only shows the notification once. After that even if I disconnect/re-connect to wifi and unplug/plug the cable, it won't show the notification.

val notificationTriggerConstraint = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.UNMETERED)
            .setRequiresCharging(true)
            .build()
    val notificationWorker = OneTimeWorkRequest.Builder(NotificationWorker::class.java)
            .setConstraints(notificationTriggerConstraint)
            .build()


class NotificationWorker(@NonNull context: Context, @NonNull workerParameters: WorkerParameters) : Worker(context, workerParameters) {
override fun doWork(): Result {

    val notificationBuilder = NotificationCompat.Builder(applicationContext, "CHANNEL")
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Background job")
            .setContentText("Device is charging and connected to WIFI")
            .setStyle(NotificationCompat.BigTextStyle().bigText("Device is charging and connected to WIFI"))
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    val notificationManager = NotificationManagerCompat.from(applicationContext)
    notificationManager.notify(0, notificationBuilder.build())

    return Result.SUCCESS
}}

这些是约束和创建通知的工作程序.我不能使用PeriodicWorkRequest,因为那不是应用程序应该工作的方式.有人可以在这里建议一种方法吗?谢谢

These are the constraints and the worker which creates the notification. I can't use a PeriodicWorkRequest since that is not the way the application should work. Can anyone suggest an approach here? Thank you

推荐答案

在这种情况下,我认为WorkManager不是最佳选择.

在您的特定情况下,您正在使用OneTimeWorkRequest,因此一旦由WorkManager运行它,就需要再次将其排队(但是,只有当两个对比方法之一为假时才将其排队是很棘手的).

In your particular case, you are using a OneTimeWorkRequest so, once this is run by the WorkManager, you need to enqueue it again (but it becomes tricky to enqueue it only when one of the two contrastraints are false).

更好的方法是结合使用 ConnectivityManager .

A better approach would be to use a combination of the BatteryManager and the ConnectivityManager.

这篇关于我想安排一个工作人员在设备插入并连接到互联网时显示通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆