Middle
What types of WorkRequest do you know and what criteria can be applied to them?
sobes.tech AI
Answer from AI
Types of WorkRequest:
- OneTimeWorkRequest: Executed once when its constraints are satisfied.
- PeriodicWorkRequest: Executed repeatedly at a specified interval.
Constraints that can be applied to a WorkRequest:
setRequiredNetworkType(NetworkType networkType): Type of required network (CONNECTED, UNMETERED, NOT_ROAMING, METERED, NOT_REQUIRED).setRequiresCharging(boolean requiresCharging): Whether device charging is required.setRequiresDeviceIdle(boolean requiresDeviceIdle): Whether the device needs to be idle.setRequiresBatteryNotLow(boolean requiresBatteryNotLow): Whether the battery level should not be low.setRequiresStorageNotLow(boolean requiresStorageNotLow): Whether storage should not be low.addContentUriTrigger(Uri uri, boolean triggerContentMaxDelay): Trigger on content change at the specified Uri.setTriggerContentUpdateDelay(long duration, TimeUnit unit): Delay before starting after content change (for OneTimeWorkRequest).setTriggerContentMaxDelay(long duration, TimeUnit unit): Maximum delay before starting after content change (for PeriodicWorkRequest).
Example of creating a OneTimeWorkRequest with constraints:
// Create constraints
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresCharging(true)
.build()
// Create OneTimeWorkRequest with constraints
val workRequest = OneTimeWorkRequestBuilder<MyWorker>()
.setConstraints(constraints)
.build()
Example of creating a PeriodicWorkRequest with constraints:
// Create constraints
val constraints = Constraints.Builder()
.setRequiresDeviceIdle(true)
.build()
// Create PeriodicWorkRequest with constraints
val periodicWorkRequest = PeriodicWorkRequestBuilder<MyWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build()