Vsevolod Ganin
Vsevolod Ganin

Reputation: 616

How to test on device with WorkManager's `setRequiresDeviceIdle(true)`

I'm trying to setup androidx WorkManager to do some job once a day.

I'm setting my job like this

val request = PeriodicWorkRequest.Builder(Worker::class.java, 24, TimeUnit.HOURS)
        .setConstraints(
                Constraints.Builder()
                        .setRequiresCharging(true)
                        .setRequiredNetworkType(NetworkType.UNMETERED)
                        .setRequiresDeviceIdle(true)
                        .build()
        )
        .build()

workManager.enqueueUniquePeriodicWork(
        "my-job-name",
        ExistingPeriodicWorkPolicy.REPLACE,
        request
)

And my Worker class has some logging.

I'm trying to verify that this is working. The problem is I can't see any of my logging in logcat. However it works fine when I remove setRequiresDeviceIdle(true) constraint. Can anyone point out how can I put my phone in the state which works with setRequiresDeviceIdle(true)?

I tried

adb shell dumpsys deviceidle force-idle

But this isn't working. Also I tried turning off screen and forwarding clocks to next day and so on. Nothing worked.

Upvotes: 0

Views: 936

Answers (1)

pfmaggi
pfmaggi

Reputation: 6506

If it's testing that were talking about, the best option is to use WorkManager's WorkManagerTestInitHelper and its capability to drive directly the testDriver.

// Create request
val workManager = WorkManager.getInstance(context)
val testDriver = WorkManagerTestInitHelper.getTestDriver()

testDriver.setAllConstraintsMet(request.id)

You can find more information in the testing documentation

Upvotes: 1

Related Questions