I want to schedule a worker to show a notification when the device is plugged in and connected to the internet

痞子三分冷 提交于 2019-12-11 18:33:04

问题


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
}}

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


回答1:


I don't think that WorkManager is the best option in this case.

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).

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



来源:https://stackoverflow.com/questions/53046545/i-want-to-schedule-a-worker-to-show-a-notification-when-the-device-is-plugged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!