问题
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