Builder
class Builder
kotlin.Any | |
↳ | android.app.job.JobInfo.Builder |
Builder class for constructing JobInfo
objects.
Summary
Public constructors | |
---|---|
Builder(jobId: Int, jobService: ComponentName) Initialize a new Builder to construct a |
Public methods | |
---|---|
JobInfo.Builder |
addDebugTag(tag: String) Add a debug tag to help track what this job is for. |
JobInfo.Builder! |
Add a new content: URI that will be monitored with a |
JobInfo! |
build() |
JobInfo.Builder |
removeDebugTag(tag: String) Remove a tag set via |
JobInfo.Builder! |
setBackoffCriteria(initialBackoffMillis: Long, backoffPolicy: Int) Set up the back-off/retry policy. |
JobInfo.Builder! |
setClipData(clip: ClipData?, grantFlags: Int) Set a |
JobInfo.Builder! |
setEstimatedNetworkBytes(downloadBytes: Long, uploadBytes: Long) Set the estimated size of network traffic that will be performed by this job, in bytes. |
JobInfo.Builder |
setExpedited(expedited: Boolean) Setting this to true indicates that this job is important and needs to run as soon as possible with stronger guarantees than regular jobs. |
JobInfo.Builder! |
setExtras(extras: PersistableBundle) Set optional extras. |
JobInfo.Builder! |
setImportantWhileForeground(importantWhileForeground: Boolean) Setting this to true indicates that this job is important while the scheduling app is in the foreground or on the temporary allowlist for background restrictions. |
JobInfo.Builder! |
setMinimumLatency(minLatencyMillis: Long) Specify that this job should be delayed by the provided amount of time. |
JobInfo.Builder |
setMinimumNetworkChunkBytes(chunkSizeBytes: Long) Set the minimum size of non-resumable network traffic this job requires, in bytes. |
JobInfo.Builder! |
setOverrideDeadline(maxExecutionDelayMillis: Long) Set a deadline after which all other functional requested constraints will be ignored. |
JobInfo.Builder! |
setPeriodic(intervalMillis: Long) Specify that this job should recur with the provided interval, not more than once per period. |
JobInfo.Builder! |
setPeriodic(intervalMillis: Long, flexMillis: Long) Specify that this job should recur with the provided interval and flex. |
JobInfo.Builder! |
setPersisted(isPersisted: Boolean) Set whether or not to persist this job across device reboots. |
JobInfo.Builder! |
setPrefetch(prefetch: Boolean) Setting this to true indicates that this job is designed to prefetch content that will make a material improvement to the experience of the specific user of this device. |
JobInfo.Builder |
setPriority(priority: Int) Indicate the priority for this job. |
JobInfo.Builder! |
setRequiredNetwork(networkRequest: NetworkRequest?) Set detailed description of the kind of network your job requires. |
JobInfo.Builder! |
setRequiredNetworkType(networkType: Int) Set basic description of the kind of network your job requires. |
JobInfo.Builder! |
setRequiresBatteryNotLow(batteryNotLow: Boolean) Specify that to run this job, the device's battery level must not be low. |
JobInfo.Builder! |
setRequiresCharging(requiresCharging: Boolean) Specify that to run this job, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices). |
JobInfo.Builder! |
setRequiresDeviceIdle(requiresDeviceIdle: Boolean) When set |
JobInfo.Builder! |
setRequiresStorageNotLow(storageNotLow: Boolean) Specify that to run this job, the device's available storage must not be low. |
JobInfo.Builder |
setTraceTag(traceTag: String?) Set a tag that will be used in |
JobInfo.Builder! |
setTransientExtras(extras: Bundle) Set optional transient extras. |
JobInfo.Builder! |
setTriggerContentMaxDelay(durationMs: Long) Set the maximum total delay (in milliseconds) that is allowed from the first time a content change is detected until the job is scheduled. |
JobInfo.Builder! |
setTriggerContentUpdateDelay(durationMs: Long) Set the delay (in milliseconds) from when a content change is detected until the job is scheduled. |
JobInfo.Builder |
setUserInitiated(userInitiated: Boolean) Indicates that this job is being scheduled to fulfill an explicit user request. |
Public constructors
Builder
Builder(
jobId: Int,
jobService: ComponentName)
Initialize a new Builder to construct a JobInfo
.
Parameters | |
---|---|
jobId |
Int: Application-provided id for this job. Subsequent calls to cancel, or jobs created with the same jobId, will update the pre-existing job with the same id. This ID must be unique across all clients of the same uid (not just the same package). You will want to make sure this is a stable id across app updates, so probably not based on a resource ID. |
jobService |
ComponentName: The endpoint that you implement that will receive the callback from the JobScheduler. This value cannot be null . |
Public methods
addDebugTag
fun addDebugTag(tag: String): JobInfo.Builder
Add a debug tag to help track what this job is for. The tags may show in debug dumps or app metrics. Do not put personally identifiable information (PII) in the tag.
Tags have the following requirements:
- Tags cannot be more than 127 characters.
- Since leading and trailing whitespace can lead to hard-to-debug issues, tags should not include leading or trailing whitespace. All tags will be
trimmed
. - An empty String (after trimming) is not allowed.
- Should not have personally identifiable information (PII).
- A job cannot have more than 32 tags.
Parameters | |
---|---|
tag |
String: A debug tag that helps describe what the job is for. This value cannot be null . |
Return | |
---|---|
JobInfo.Builder |
This object for method chaining This value cannot be null . |
addTriggerContentUri
fun addTriggerContentUri(uri: JobInfo.TriggerContentUri): JobInfo.Builder!
Add a new content: URI that will be monitored with a android.database.ContentObserver
, and will cause the job to execute if changed. If you have any trigger content URIs associated with a job, it will not execute until there has been a change report for one or more of them.
Note that trigger URIs can not be used in combination with setPeriodic(long)
or setPersisted(boolean)
. To continually monitor for content changes, you need to schedule a new JobInfo using the same job ID and observing the same URIs in place of calling JobService#jobFinished(JobParameters, boolean)
. Remember that JobScheduler#schedule(JobInfo)
stops a running job if it uses the same job ID, so only call it after you've finished processing the most recent changes (in other words, call JobScheduler#schedule(JobInfo)
where you would have normally called JobService#jobFinished(JobParameters, boolean)
. Following this pattern will ensure you do not lose any content changes: while your job is running, the system will continue monitoring for content changes, and propagate any changes it sees over to the next job you schedule, so you do not have to worry about missing new changes. Scheduling the new job before or during processing will cause the current job to be stopped (as described in JobScheduler#schedule(JobInfo)
), meaning the wakelock will be released for the current job and your app process may be killed since it will no longer be in a valid component lifecycle. Since JobScheduler#schedule(JobInfo)
stops the current job, you do not need to call JobService#jobFinished(JobParameters, boolean)
if you call JobScheduler#schedule(JobInfo)
using the same job ID as the currently running job.
Because setting this property is not compatible with periodic or persisted jobs, doing so will throw an java.lang.IllegalArgumentException
when android.app.job.JobInfo.Builder#build()
is called.
The following example shows how this feature can be used to monitor for changes in the photos on a device.
Parameters | |
---|---|
uri |
JobInfo.TriggerContentUri: The content: URI to monitor. This value cannot be null . |
build
fun build(): JobInfo!
Return | |
---|---|
JobInfo! |
The job object to hand to the JobScheduler. This object is immutable. |
removeDebugTag
fun removeDebugTag(tag: String): JobInfo.Builder
Remove a tag set via addDebugTag(java.lang.String)
.
Parameters | |
---|---|
tag |
String: The tag to remove This value cannot be null . |
Return | |
---|---|
JobInfo.Builder |
This object for method chaining This value cannot be null . |
setBackoffCriteria
fun setBackoffCriteria(
initialBackoffMillis: Long,
backoffPolicy: Int
): JobInfo.Builder!
Set up the back-off/retry policy. This defaults to some respectable values: {30 seconds, Exponential}. We cap back-off at 5hrs.
Note that trying to set a backoff criteria for a job with setRequiresDeviceIdle(boolean)
will throw an exception when you call build(). This is because back-off typically does not make sense for these types of jobs. See android.app.job.JobService#jobFinished(android.app.job.JobParameters, boolean)
for more description of the return value for the case of a job executing while in idle mode.
Parameters | |
---|---|
initialBackoffMillis |
Long: Millisecond time interval to wait initially when job has failed. |
backoffPolicy |
Int: Value is android.app.job.JobInfo#BACKOFF_POLICY_LINEAR , or android.app.job.JobInfo#BACKOFF_POLICY_EXPONENTIAL |
setClipData
fun setClipData(
clip: ClipData?,
grantFlags: Int
): JobInfo.Builder!
Set a ClipData
associated with this Job.
The main purpose of providing a ClipData is to allow granting of URI permissions for data associated with the clip. The exact kind of permission grant to perform is specified through grantFlags.
If the ClipData contains items that are Intents, any grant flags in those Intents will be ignored. Only flags provided as an argument to this method are respected, and will be applied to all Uri or Intent items in the clip (or sub-items of the clip).
Because setting this property is not compatible with persisted jobs, doing so will throw an java.lang.IllegalArgumentException
when android.app.job.JobInfo.Builder#build()
is called.
Parameters | |
---|---|
clip |
ClipData?: The new clip to set. May be null to clear the current clip. |
grantFlags |
Int: The desired permissions to grant for any URIs. This should be a combination of android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION , android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION , and android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION . |
setEstimatedNetworkBytes
fun setEstimatedNetworkBytes(
downloadBytes: Long,
uploadBytes: Long
): JobInfo.Builder!
Set the estimated size of network traffic that will be performed by this job, in bytes.
Apps are encouraged to provide values that are as accurate as possible, but when the exact size isn't available, an order-of-magnitude estimate can be provided instead. Here are some specific examples:
- A job that is backing up a photo knows the exact size of that photo, so it should provide that size as the estimate.
- A job that refreshes top news stories wouldn't know an exact size, but if the size is expected to be consistently around 100KB, it can provide that order-of-magnitude value as the estimate.
- A job that synchronizes email could end up using an extreme range of data, from under 1KB when nothing has changed, to dozens of MB when there are new emails with attachments. Jobs that cannot provide reasonable estimates should use the sentinel value
JobInfo#NETWORK_BYTES_UNKNOWN
.
Build.VERSION_CODES#S
, JobScheduler may attempt to run large jobs when the device is charging and on an unmetered network, even if the network is slow. This gives large jobs an opportunity to make forward progress, even if they risk timing out.
The values provided here only reflect the traffic that will be performed by the base job; if you're using JobWorkItem
then you also need to define the network traffic used by each work item when constructing them.
Prior to Android version Build.VERSION_CODES#TIRAMISU
, JobScheduler used the estimated transfer numbers in a similar fashion to setMinimumNetworkChunkBytes(long)
(to estimate if the work would complete within the time available to job). In other words, JobScheduler treated the transfer as all-or-nothing. Starting from Android version Build.VERSION_CODES#TIRAMISU
, JobScheduler will only use the estimated transfer numbers in this manner if minimum chunk sizes have not been provided via setMinimumNetworkChunkBytes(long)
.
Parameters | |
---|---|
downloadBytes |
Long: The estimated size of network traffic that will be downloaded by this job, in bytes. Value is a non-negative number of bytes. |
uploadBytes |
Long: The estimated size of network traffic that will be uploaded by this job, in bytes. Value is a non-negative number of bytes. |
setExpedited
fun setExpedited(expedited: Boolean): JobInfo.Builder
Setting this to true indicates that this job is important and needs to run as soon as possible with stronger guarantees than regular jobs. These "expedited" jobs will:
- Run as soon as possible
- Be less restricted during Doze and battery saver
- Bypass Doze, app standby, and battery saver network restrictions (if the job has a
connectivity constraint
) - Be less likely to be killed than regular jobs
- Be subject to background location throttling
- Be exempt from delay to optimize job execution
Expedited jobs are given PRIORITY_MAX
by default.
Since these jobs have stronger guarantees than regular jobs, they will be subject to stricter quotas. As long as an app has available expedited quota, jobs scheduled with this set to true will run with these guarantees. If an app has run out of available expedited quota, any pending expedited jobs will run as regular jobs. JobParameters#isExpeditedJob()
can be used to know whether the executing job has expedited guarantees or not. In addition, JobScheduler#schedule(JobInfo)
will immediately return JobScheduler#RESULT_FAILURE
if the app does not have available quota (and the job will not be successfully scheduled).
Expedited job quota will replenish over time and as the user interacts with the app, so you should not have to worry about running out of quota because of processing from frequent user engagement.
Expedited jobs may only set network, storage-not-low, and persistence constraints. No other constraints are allowed.
Assuming all constraints remain satisfied (including ideal system load conditions), expedited jobs can have an execution time of at least 1 minute. If your app has remaining expedited job quota, then the expedited job may potentially run longer until remaining quota is used up. Just like with regular jobs, quota is not consumed while the app is on top and visible to the user.
Note: Even though expedited jobs are meant to run as soon as possible, they may be deferred if the system is under heavy load or requested constraints are not satisfied. This delay may be true for expedited jobs of the foreground app on Android version Build.VERSION_CODES#S
, but starting from Android version Build.VERSION_CODES#TIRAMISU
, expedited jobs for the foreground app are guaranteed to be started before JobScheduler#schedule(JobInfo)
returns (assuming all requested constraints are satisfied), similar to foreground services.
Return | |
---|---|
JobInfo.Builder |
This value cannot be null . |
setExtras
fun setExtras(extras: PersistableBundle): JobInfo.Builder!
Set optional extras. This is persisted, so we only allow primitive types.
Parameters | |
---|---|
extras |
PersistableBundle: Bundle containing extras you want the scheduler to hold on to for you. This value cannot be null . |
See Also
setImportantWhileForeground
funsetImportantWhileForeground(importantWhileForeground: Boolean): JobInfo.Builder!
Deprecated: Use setExpedited(boolean)
instead.
Setting this to true indicates that this job is important while the scheduling app is in the foreground or on the temporary allowlist for background restrictions. This means that the system will relax doze restrictions on this job during this time. Apps should use this flag only for short jobs that are essential for the app to function properly in the foreground. Note that once the scheduling app is no longer allowlisted from background restrictions and in the background, or the job failed due to unsatisfied constraints, this job should be expected to behave like other jobs without this flag.
Jobs marked as important-while-foreground are given PRIORITY_HIGH
by default.
Parameters | |
---|---|
importantWhileForeground |
Boolean: whether to relax doze restrictions for this job when the app is in the foreground. False by default. |
setMinimumLatency
fun setMinimumLatency(minLatencyMillis: Long): JobInfo.Builder!
Specify that this job should be delayed by the provided amount of time. The job may not run the instant the delay has elapsed. JobScheduler will start the job at an indeterminate time after the delay has elapsed.
Because it doesn't make sense setting this property on a periodic job, doing so will throw an java.lang.IllegalArgumentException
when android.app.job.JobInfo.Builder#build()
is called. Negative latencies also don't make sense for a job and are indicative of an error, so starting in Android version android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM
, setting a negative deadline will result in android.app.job.JobInfo.Builder#build()
throwing an java.lang.IllegalArgumentException
.
Parameters | |
---|---|
minLatencyMillis |
Long: Milliseconds before which this job will not be considered for execution. |
setMinimumNetworkChunkBytes
fun setMinimumNetworkChunkBytes(chunkSizeBytes: Long): JobInfo.Builder
Set the minimum size of non-resumable network traffic this job requires, in bytes. When the upload or download can be easily paused and resumed, use this to set the smallest size that must be transmitted between start and stop events to be considered successful. If the transfer cannot be paused and resumed, then this should be the sum of the values provided to JobInfo.Builder#setEstimatedNetworkBytes(long, long)
.
Apps are encouraged to provide values that are as accurate as possible since JobScheduler will try to run the job at a time when at least the minimum chunk can be transmitted to reduce the amount of repetitive data that's transferred. Jobs that cannot provide reasonable estimates should use the sentinel value JobInfo#NETWORK_BYTES_UNKNOWN
.
The values provided here only reflect the minimum non-resumable traffic that will be performed by the base job; if you're using JobWorkItem
then you also need to define the network traffic used by each work item when constructing them.
Parameters | |
---|---|
chunkSizeBytes |
Long: The smallest piece of data that cannot be easily paused and resumed, in bytes. Value is a non-negative number of bytes. |
Return | |
---|---|
JobInfo.Builder |
This value cannot be null . |
setOverrideDeadline
fun setOverrideDeadline(maxExecutionDelayMillis: Long): JobInfo.Builder!
Set a deadline after which all other functional requested constraints will be ignored. After the deadline has passed, the job can run even if other requirements (including a delay set through setMinimumLatency(long)
) are not met. JobParameters#isOverrideDeadlineExpired()
will return true
if the job's deadline has passed. The job's execution may be delayed beyond the set deadline by other factors such as Doze mode and system health signals.
Because it doesn't make sense setting this property on a periodic job, doing so will throw an java.lang.IllegalArgumentException
when android.app.job.JobInfo.Builder#build()
is called.
Negative deadlines also don't make sense for a job and are indicative of an error, so starting in Android version android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM
, setting a negative deadline will result in android.app.job.JobInfo.Builder#build()
throwing an java.lang.IllegalArgumentException
.
Since a job will run once the deadline has passed regardless of the status of other constraints, setting a deadline of 0 (or a delay
equal to the deadline) with other constraints makes those constraints meaningless when it comes to execution decisions. Since doing so is indicative of an error in the logic, starting in Android version android.os.Build.VERSION_CODES#VANILLA_ICE_CREAM
, jobs with extremely short time windows will fail to build. Time windows are defined as the time between a job's minimum latency
and its deadline. If the minimum latency is not set, it is assumed to be 0. Work that must happen immediately should use setExpedited(boolean)
or setUserInitiated(boolean)
in the appropriate manner.
This API aimed to guarantee execution of the job by the deadline only on Android version android.os.Build.VERSION_CODES#LOLLIPOP
. That aim and guarantee has not existed since android.os.Build.VERSION_CODES#M
.
setPeriodic
fun setPeriodic(intervalMillis: Long): JobInfo.Builder!
Specify that this job should recur with the provided interval, not more than once per period. You have no control over when within this interval this job will be executed, only the guarantee that it will be executed at most once within this interval, as long as the constraints are satisfied. If the constraints are not satisfied within this interval, the job will wait until the constraints are satisfied. Setting this function on the builder with setMinimumLatency(long)
or setOverrideDeadline(long)
will result in an error.
Parameters | |
---|---|
intervalMillis |
Long: Millisecond interval for which this job will repeat. |
setPeriodic
fun setPeriodic(
intervalMillis: Long,
flexMillis: Long
): JobInfo.Builder!
Specify that this job should recur with the provided interval and flex. The job can execute at any time in a window of flex length at the end of the period. If the constraints are not satisfied within the window, the job will wait until the constraints are satisfied.
Parameters | |
---|---|
intervalMillis |
Long: Millisecond interval for which this job will repeat. A minimum value of getMinPeriodMillis() is enforced. |
flexMillis |
Long: Millisecond flex for this job. Flex is clamped to be at least getMinFlexMillis() or 5 percent of the period, whichever is higher. |
setPersisted
fun setPersisted(isPersisted: Boolean): JobInfo.Builder!
Set whether or not to persist this job across device reboots.
Requires android.Manifest.permission#RECEIVE_BOOT_COMPLETED
Parameters | |
---|---|
isPersisted |
Boolean: True to indicate that the job will be written to disk and loaded at boot. |
setPrefetch
fun setPrefetch(prefetch: Boolean): JobInfo.Builder!
Setting this to true indicates that this job is designed to prefetch content that will make a material improvement to the experience of the specific user of this device. For example, fetching top headlines of interest to the current user.
Apps targeting Android version Build.VERSION_CODES#TIRAMISU
or later are not allowed to have deadlines (set via setOverrideDeadline(long)
on their prefetch jobs.
The system may use this signal to relax the network constraints you originally requested, such as allowing a JobInfo#NETWORK_TYPE_UNMETERED
job to run over a metered network when there is a surplus of metered data available. The system may also use this signal in combination with end user usage patterns to ensure data is prefetched before the user launches your app.
See Also
setPriority
fun setPriority(priority: Int): JobInfo.Builder
Indicate the priority for this job. The priority set here will be used to sort jobs for the calling app and apply slightly different policies based on the priority. The priority will NOT be used as a global sorting value to sort between different app's jobs. Use this to inform the system about which jobs it should try to run before other jobs. Giving the same priority to all of your jobs will result in them all being treated the same. The priorities each have slightly different behaviors, as noted in their relevant javadoc. Starting in Android version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE
, the priority will only affect sorting order within the job's namespace. NOTE: Setting all of your jobs to high priority will not be beneficial to your app and in fact may hurt its performance in the long run. In order to prevent starvation, repeatedly retried jobs (because of failures) will slowly have their priorities lowered.
Return | |
---|---|
JobInfo.Builder |
This value cannot be null . |
setRequiredNetwork
fun setRequiredNetwork(networkRequest: NetworkRequest?): JobInfo.Builder!
Set detailed description of the kind of network your job requires.
If your job doesn't need a network connection, you don't need to call this method, as the default is null
.
Calling this method defines network as a strict requirement for your job. If the network requested is not available your job will never run. See setOverrideDeadline(long)
to change this behavior. Calling this method will override any requirements previously defined by setRequiredNetworkType(int)
; you typically only want to call one of these methods.
When your job executes in JobService#onStartJob(JobParameters)
, be sure to use the specific network returned by JobParameters#getNetwork()
, otherwise you'll use the default network which may not meet this constraint. Starting in Android version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE
, an app must hold the android.Manifest.permission#ACCESS_NETWORK_STATE
permission to schedule a job that requires a network.
Parameters | |
---|---|
networkRequest |
NetworkRequest?: The detailed description of the kind of network this job requires, or null if no specific kind of network is required. Defining a NetworkSpecifier is only supported for jobs that aren't persisted. |
setRequiredNetworkType
fun setRequiredNetworkType(networkType: Int): JobInfo.Builder!
Set basic description of the kind of network your job requires. If you need more precise control over network capabilities, see setRequiredNetwork(android.net.NetworkRequest)
.
If your job doesn't need a network connection, you don't need to call this method, as the default value is NETWORK_TYPE_NONE
.
Calling this method defines network as a strict requirement for your job. If the network requested is not available your job will never run. See setOverrideDeadline(long)
to change this behavior. Calling this method will override any requirements previously defined by setRequiredNetwork(android.net.NetworkRequest)
; you typically only want to call one of these methods. Starting in Android version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE
, an app must hold the android.Manifest.permission#ACCESS_NETWORK_STATE
permission to schedule a job that requires a network.
Starting in Android version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE
, JobScheduler
may try to shift the execution of jobs requiring NETWORK_TYPE_ANY
to when there is access to an un-metered network.
When your job executes in JobService#onStartJob(JobParameters)
, be sure to use the specific network returned by JobParameters#getNetwork()
, otherwise you'll use the default network which may not meet this constraint.
setRequiresBatteryNotLow
fun setRequiresBatteryNotLow(batteryNotLow: Boolean): JobInfo.Builder!
Specify that to run this job, the device's battery level must not be low. This defaults to false. If true, the job will only run when the battery level is not low, which is generally the point where the user is given a "low battery" warning. Setting this to false
DOES NOT mean the job will only run when the battery is low.
Parameters | |
---|---|
batteryNotLow |
Boolean: Whether or not the device's battery level must not be low. |
setRequiresCharging
fun setRequiresCharging(requiresCharging: Boolean): JobInfo.Builder!
Specify that to run this job, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices). This defaults to false
. Setting this to false
DOES NOT mean the job will only run when the device is not charging.
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.
Parameters | |
---|---|
requiresCharging |
Boolean: Pass true to require that the device be charging in order to run the job. |
setRequiresDeviceIdle
fun setRequiresDeviceIdle(requiresDeviceIdle: Boolean): JobInfo.Builder!
When set true
, ensure that this job will not run if the device is in active use. The default state is false
: that is, the for the job to be runnable even when someone is interacting with the device. Setting this to false
DOES NOT mean the job will only run when the device is not idle.
This state is a loose definition provided by the system. In general, it means that the device is not currently being used interactively, and has not been in use for some time. As such, it is a good time to perform resource heavy jobs. Bear in mind that battery usage will still be attributed to your application, and surfaced to the user in battery stats.
Despite the similar naming, this job constraint is not related to the system's "device idle" or "doze" states. This constraint only determines whether a job is allowed to run while the device is directly in use.
Parameters | |
---|---|
requiresDeviceIdle |
Boolean: Pass true to prevent the job from running while the device is being used interactively. |
setRequiresStorageNotLow
fun setRequiresStorageNotLow(storageNotLow: Boolean): JobInfo.Builder!
Specify that to run this job, the device's available storage must not be low. This defaults to false. If true, the job will only run when the device is not in a low storage state, which is generally the point where the user is given a "low storage" warning.
Parameters | |
---|---|
storageNotLow |
Boolean: Whether or not the device's available storage must not be low. |
setTraceTag
fun setTraceTag(traceTag: String?): JobInfo.Builder
Set a tag that will be used in traces
. Since this is a trace tag, it must follow the rules set in android.os.Trace#beginSection(String)
, such as it cannot be more than 127 Unicode code units. Additionally, since leading and trailing whitespace can lead to hard-to-debug issues, they will be trimmed
. An empty String (after trimming) is not allowed.
Parameters | |
---|---|
traceTag |
String?: The tag to use in traces. This value may be null . |
Return | |
---|---|
JobInfo.Builder |
This object for method chaining This value cannot be null . |
setTransientExtras
fun setTransientExtras(extras: Bundle): JobInfo.Builder!
Set optional transient extras.
Because setting this property is not compatible with persisted jobs, doing so will throw an java.lang.IllegalArgumentException
when android.app.job.JobInfo.Builder#build()
is called.
Parameters | |
---|---|
extras |
Bundle: Bundle containing extras you want the scheduler to hold on to for you. This value cannot be null . |
setTriggerContentMaxDelay
fun setTriggerContentMaxDelay(durationMs: Long): JobInfo.Builder!
Set the maximum total delay (in milliseconds) that is allowed from the first time a content change is detected until the job is scheduled.
Parameters | |
---|---|
durationMs |
Long: Delay after initial content change, in milliseconds. |
setTriggerContentUpdateDelay
fun setTriggerContentUpdateDelay(durationMs: Long): JobInfo.Builder!
Set the delay (in milliseconds) from when a content change is detected until the job is scheduled. If there are more changes during that time, the delay will be reset to start at the time of the most recent change.
Parameters | |
---|---|
durationMs |
Long: Delay after most recent content change, in milliseconds. |
setUserInitiated
fun setUserInitiated(userInitiated: Boolean): JobInfo.Builder
Indicates that this job is being scheduled to fulfill an explicit user request. As such, user-initiated jobs can only be scheduled when the app is in the foreground or in a state where launching an activity is allowed, as defined here. Attempting to schedule one outside of these conditions will return a JobScheduler#RESULT_FAILURE
.
This should NOT be used for automatic features.
All user-initiated jobs must have an associated notification, set via JobService#setNotification(JobParameters, int, Notification, int)
, and will be shown in the Task Manager when running. These jobs cannot be rescheduled by the app if the user stops the job via system provided affordance (such as the Task Manager). Thus, it is best practice and recommended to provide action buttons in the associated notification to allow the user to stop the job gracefully and allow for rescheduling.
If the app doesn't hold the android.Manifest.permission#RUN_USER_INITIATED_JOBS
permission when scheduling a user-initiated job, JobScheduler will throw a SecurityException
.
In android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE
, user-initiated jobs can only be used for network data transfers. As such, they must specify a required network via setRequiredNetwork(android.net.NetworkRequest)
or setRequiredNetworkType(int)
.
These jobs will not be subject to quotas and will be started immediately once scheduled if all constraints are met and the device system health allows for additional tasks. They are also given PRIORITY_MAX
by default, and the priority cannot be changed.
Requires android.Manifest.permission#RUN_USER_INITIATED_JOBS
Return | |
---|---|
JobInfo.Builder |
This value cannot be null . |