Search code examples
androidkotlinandroid-broadcastandroid-workmanager

Charging constraint not working properly in WorkManager In Android Kotlin


I wrote this code and gave two constraints:

  1. Network is connected
  2. Charger is connected

but when I disconnect the charger and put the code enqueue and plugin the charger again it does not run and stays at enqueue state while the network constraint is working just fine.

Activity Class

class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    val viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
    binding.button.setOnClickListener {
        setWorkManager()
    }
}

private fun setWorkManager() {
    val workManager =  WorkManager.getInstance(applicationContext)
    val constrains = Constraints.Builder()
        .setRequiresCharging(true)
        .build()

    val uploadRequest = OneTimeWorkRequestBuilder<MyWorker>()
        .setConstraints(constrains)
        .build()

    workManager.enqueue(uploadRequest)
}

}

Worker Class

class MyWorker(
    context: Context,
    param: WorkerParameters) :  Worker(context, param) {

    override fun doWork(): Result {
        return try {
            for (i in 0..600) {
                Log.i("check", "in $i")
            }
            Result.success()
        } catch (e: Exception) {
            Result.failure()
        }
    }
}

Solution

  • Your code looks correct.

    WorkManager's setRequiresCharging() is built on top JobScheduler's setRequiresCharging() and it may have sometimes surprising behaviors. From JobScheduler documentation:

    For purposes of running jobs, a battery-powered device "charging" is not quite the same as simply being connected to power. If the device is so busy that the battery is draining despite a power connection, jobs with this constraint will not run. This can happen during some common use cases such as video chat, particularly if the device is plugged in to USB rather than to wall power.

    I also saw that sometimes, on the emulator, you need to set the device as charging and then increase the battery charge to see your work to be scheduled.