lightbulb_outline Help shape the future of the Google Play Console, Android Studio, and Firebase. Start survey

JobInfo.Builder

public static final class JobInfo.Builder
extends Object

java.lang.Object
   ↳ android.app.job.JobInfo.Builder


Builder class for constructing JobInfo objects.

Summary

Public constructors

JobInfo.Builder(int jobId, ComponentName jobService)

Initialize a new Builder to construct a JobInfo.

Public methods

JobInfo.Builder addTriggerContentUri(JobInfo.TriggerContentUri uri)

Add a new content: URI that will be monitored with a ContentObserver, and will cause the job to execute if changed.

JobInfo build()
JobInfo.Builder setBackoffCriteria(long initialBackoffMillis, int backoffPolicy)

Set up the back-off/retry policy.

JobInfo.Builder setClipData(ClipData clip, int grantFlags)

Set a ClipData associated with this Job.

JobInfo.Builder setEstimatedNetworkBytes(long downloadBytes, long uploadBytes)

Set the estimated size of network traffic that will be performed by this job, in bytes.

JobInfo.Builder setExtras(PersistableBundle extras)

Set optional extras.

JobInfo.Builder setImportantWhileForeground(boolean importantWhileForeground)

Setting this to true indicates that this job is important while the scheduling app is in the foreground or on the temporary whitelist for background restrictions.

JobInfo.Builder setMinimumLatency(long minLatencyMillis)

Specify that this job should be delayed by the provided amount of time.

JobInfo.Builder setOverrideDeadline(long maxExecutionDelayMillis)

Set deadline which is the maximum scheduling latency.

JobInfo.Builder setPeriodic(long intervalMillis)

Specify that this job should recur with the provided interval, not more than once per period.

JobInfo.Builder setPeriodic(long intervalMillis, long flexMillis)

Specify that this job should recur with the provided interval and flex.

JobInfo.Builder setPersisted(boolean isPersisted)

Set whether or not to persist this job across device reboots.

JobInfo.Builder setPrefetch(boolean prefetch)

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 setRequiredNetwork(NetworkRequest networkRequest)

Set detailed description of the kind of network your job requires.

JobInfo.Builder setRequiredNetworkType(int networkType)

Set basic description of the kind of network your job requires.

JobInfo.Builder setRequiresBatteryNotLow(boolean batteryNotLow)

Specify that to run this job, the device's battery level must not be low.

JobInfo.Builder setRequiresCharging(boolean requiresCharging)

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(boolean requiresDeviceIdle)

When set true, ensure that this job will not run if the device is in active use.

JobInfo.Builder setRequiresStorageNotLow(boolean storageNotLow)

Specify that to run this job, the device's available storage must not be low.

JobInfo.Builder setTransientExtras(Bundle extras)

Set optional transient extras.

JobInfo.Builder setTriggerContentMaxDelay(long durationMs)

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(long durationMs)

Set the delay (in milliseconds) from when a content change is detected until the job is scheduled.

Inherited methods

Public constructors

JobInfo.Builder

added in API level 21
public JobInfo.Builder (int jobId, 
                ComponentName jobService)

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 must never be null.

Public methods

addTriggerContentUri

added in API level 24
public JobInfo.Builder addTriggerContentUri (JobInfo.TriggerContentUri uri)

Add a new content: URI that will be monitored with a 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 observing the same URIs before you finish execution of the JobService handling the most recent changes. Following this pattern will ensure you do not lost any content changes: while your job is running, the system will continue monitoring for content changes, and propagate any it sees over to the next job you schedule.

Because setting this property is not compatible with periodic or persisted jobs, doing so will throw an IllegalArgumentException when build() is called.

The following example shows how this feature can be used to monitor for changes in the photos on a device.

import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Example stub job to monitor when there is a change to photos in the media provider.
 */
public class PhotosContentJob extends JobService {
    // The root URI of the media provider, to monitor for generic changes to its content.
    static final Uri MEDIA_URI = Uri.parse("content://" + MediaStore.AUTHORITY + "/");

    // Path segments for image-specific URIs in the provider.
    static final List<String> EXTERNAL_PATH_SEGMENTS
            = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPathSegments();

    // The columns we want to retrieve about a particular image.
    static final String[] PROJECTION = new String[] {
            MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA
    };
    static final int PROJECTION_ID = 0;
    static final int PROJECTION_DATA = 1;

    // This is the external storage directory where cameras place pictures.
    static final String DCIM_DIR = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DCIM).getPath();

    // A pre-built JobInfo we use for scheduling our job.
    static final JobInfo JOB_INFO;

    static {
        JobInfo.Builder builder = new JobInfo.Builder(JobIds.PHOTOS_CONTENT_JOB,
                new ComponentName("com.example.android.apis", PhotosContentJob.class.getName()));
        // Look for specific changes to images in the provider.
        builder.addTriggerContentUri(new JobInfo.TriggerContentUri(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
        // Also look for general reports of changes in the overall provider.
        builder.addTriggerContentUri(new JobInfo.TriggerContentUri(MEDIA_URI, 0));
        JOB_INFO = builder.build();
    }

    // Fake job work.  A real implementation would do some work on a separate thread.
    final Handler mHandler = new Handler();
    final Runnable mWorker = new Runnable() {
        @Override public void run() {
            scheduleJob(PhotosContentJob.this);
            jobFinished(mRunningParams, false);
        }
    };

    JobParameters mRunningParams;

    // Schedule this job, replace any existing one.
    public static void scheduleJob(Context context) {
        JobScheduler js = context.getSystemService(JobScheduler.class);
        js.schedule(JOB_INFO);
        Log.i("PhotosContentJob", "JOB SCHEDULED!");
    }

    // Check whether this job is currently scheduled.
    public static boolean isScheduled(Context context) {
        JobScheduler js = context.getSystemService(JobScheduler.class);
        List<JobInfo> jobs = js.getAllPendingJobs();
        if (jobs == null) {
            return false;
        }
        for (int i=0; i<jobs.size(); i++) {
            if (jobs.get(i).getId() == JobIds.PHOTOS_CONTENT_JOB) {
                return true;
            }
        }
        return false;
    }

    // Cancel this job, if currently scheduled.
    public static void cancelJob(Context context) {
        JobScheduler js = context.getSystemService(JobScheduler.class);
        js.cancel(JobIds.PHOTOS_CONTENT_JOB);
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.i("PhotosContentJob", "JOB STARTED!");
        mRunningParams = params;

        // Instead of real work, we are going to build a string to show to the user.
        StringBuilder sb = new StringBuilder();

        // Did we trigger due to a content change?
        if (params.getTriggeredContentAuthorities() != null) {
            boolean rescanNeeded = false;

            if (params.getTriggeredContentUris() != null) {
                // If we have details about which URIs changed, then iterate through them
                // and collect either the ids that were impacted or note that a generic
                // change has happened.
                ArrayList<String> ids = new ArrayList<>();
                for (Uri uri : params.getTriggeredContentUris()) {
                    List<String> path = uri.getPathSegments();
                    if (path != null && path.size() == EXTERNAL_PATH_SEGMENTS.size()+1) {
                        // This is a specific file.
                        ids.add(path.get(path.size()-1));
                    } else {
                        // Oops, there is some general change!
                        rescanNeeded = true;
                    }
                }

                if (ids.size() > 0) {
                    // If we found some ids that changed, we want to determine what they are.
                    // First, we do a query with content provider to ask about all of them.
                    StringBuilder selection = new StringBuilder();
                    for (int i=0; i<ids.size(); i++) {
                        if (selection.length() > 0) {
                            selection.append(" OR ");
                        }
                        selection.append(MediaStore.Images.ImageColumns._ID);
                        selection.append("='");
                        selection.append(ids.get(i));
                        selection.append("'");
                    }

                    // Now we iterate through the query, looking at the filenames of
                    // the items to determine if they are ones we are interested in.
                    Cursor cursor = null;
                    boolean haveFiles = false;
                    try {
                        cursor = getContentResolver().query(
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                PROJECTION, selection.toString(), null, null);
                        while (cursor.moveToNext()) {
                            // We only care about files in the DCIM directory.
                            String dir = cursor.getString(PROJECTION_DATA);
                            if (dir.startsWith(DCIM_DIR)) {
                                if (!haveFiles) {
                                    haveFiles = true;
                                    sb.append("New photos:\n");
                                }
                                sb.append(cursor.getInt(PROJECTION_ID));
                                sb.append(": ");
                                sb.append(dir);
                                sb.append("\n");
                            }
                        }
                    } catch (SecurityException e) {
                        sb.append("Error: no access to media!");
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }

            } else {
                // We don't have any details about URIs (because too many changed at once),
                // so just note that we need to do a full rescan.
                rescanNeeded = true;
            }

            if (rescanNeeded) {
                sb.append("Photos rescan needed!");
            }
        } else {
            sb.append("(No photos content)");
        }
        Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();

        // We will emulate taking some time to do this work, so we can see batching happen.
        mHandler.postDelayed(mWorker, 10*1000);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        mHandler.removeCallbacks(mWorker);
        return false;
    }
}

Parameters
uri JobInfo.TriggerContentUri: The content: URI to monitor.

This value must never be null.

Returns
JobInfo.Builder

build

added in API level 21
public JobInfo build ()

Returns
JobInfo The job object to hand to the JobScheduler. This object is immutable.

setBackoffCriteria

added in API level 21
public JobInfo.Builder setBackoffCriteria (long initialBackoffMillis, 
                int backoffPolicy)

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 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 BACKOFF_POLICY_LINEAR or BACKOFF_POLICY_EXPONENTIAL.

Returns
JobInfo.Builder

setClipData

added in API level 26
public JobInfo.Builder setClipData (ClipData clip, 
                int grantFlags)

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 IllegalArgumentException when 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 Intent.FLAG_GRANT_READ_URI_PERMISSION, Intent.FLAG_GRANT_WRITE_URI_PERMISSION, and Intent.FLAG_GRANT_PREFIX_URI_PERMISSION.

Returns
JobInfo.Builder

setEstimatedNetworkBytes

added in API level 28
public JobInfo.Builder setEstimatedNetworkBytes (long downloadBytes, 
                long uploadBytes)

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.
Note that the system may choose to delay jobs with large network usage estimates when the device has a poor network connection, in order to save battery.

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.

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.

Returns
JobInfo.Builder

setExtras

added in API level 21
public JobInfo.Builder setExtras (PersistableBundle extras)

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 must never be null.

Returns
JobInfo.Builder

setImportantWhileForeground

added in API level 28
public JobInfo.Builder setImportantWhileForeground (boolean importantWhileForeground)

Setting this to true indicates that this job is important while the scheduling app is in the foreground or on the temporary whitelist 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 whitelisted 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.

Parameters
importantWhileForeground boolean: whether to relax doze restrictions for this job when the app is in the foreground. False by default.

Returns
JobInfo.Builder

setMinimumLatency

added in API level 21
public JobInfo.Builder setMinimumLatency (long minLatencyMillis)

Specify that this job should be delayed by the provided amount of time. Because it doesn't make sense setting this property on a periodic job, doing so will throw an IllegalArgumentException when build() is called.

Parameters
minLatencyMillis long: Milliseconds before which this job will not be considered for execution.

Returns
JobInfo.Builder

setOverrideDeadline

added in API level 21
public JobInfo.Builder setOverrideDeadline (long maxExecutionDelayMillis)

Set deadline which is the maximum scheduling latency. The job will be run by this deadline even if other requirements are not met. Because it doesn't make sense setting this property on a periodic job, doing so will throw an IllegalArgumentException when build() is called.

Parameters
maxExecutionDelayMillis long

Returns
JobInfo.Builder

setPeriodic

added in API level 21
public JobInfo.Builder setPeriodic (long intervalMillis)

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. 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.

Returns
JobInfo.Builder

setPeriodic

added in API level 24
public JobInfo.Builder setPeriodic (long intervalMillis, 
                long flexMillis)

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.

Parameters
intervalMillis long: Millisecond interval for which this job will repeat. A minimum value of JobInfo.getMinPeriodMillis() is enforced.

flexMillis long: Millisecond flex for this job. Flex is clamped to be at least JobInfo.getMinFlexMillis() or 5 percent of the period, whichever is higher.

Returns
JobInfo.Builder

setPersisted

added in API level 21
public JobInfo.Builder setPersisted (boolean isPersisted)

Set whether or not to persist this job across device reboots.

Requires the RECEIVE_BOOT_COMPLETED permission.

Parameters
isPersisted boolean: True to indicate that the job will be written to disk and loaded at boot.

Returns
JobInfo.Builder

setPrefetch

added in API level 28
public JobInfo.Builder setPrefetch (boolean prefetch)

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.

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.

Parameters
prefetch boolean

Returns
JobInfo.Builder

setRequiredNetwork

added in API level 28
public JobInfo.Builder setRequiredNetwork (NetworkRequest networkRequest)

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.

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.

Returns
JobInfo.Builder

setRequiredNetworkType

added in API level 21
public JobInfo.Builder setRequiredNetworkType (int networkType)

Set basic description of the kind of network your job requires. If you need more precise control over network capabilities, see setRequiredNetwork(NetworkRequest).

If your job doesn't need a network connection, you don't need to call this method, as the default value is JobInfo.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(NetworkRequest); 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.

Parameters
networkType int

Value is NETWORK_TYPE_NONE, NETWORK_TYPE_ANY, NETWORK_TYPE_UNMETERED, NETWORK_TYPE_NOT_ROAMING or NETWORK_TYPE_METERED.

Returns
JobInfo.Builder

setRequiresBatteryNotLow

added in API level 26
public JobInfo.Builder setRequiresBatteryNotLow (boolean batteryNotLow)

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.

Parameters
batteryNotLow boolean: Whether or not the device's battery level must not be low.

Returns
JobInfo.Builder

setRequiresCharging

added in API level 21
public JobInfo.Builder setRequiresCharging (boolean requiresCharging)

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.

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.

Returns
JobInfo.Builder

setRequiresDeviceIdle

added in API level 21
public JobInfo.Builder setRequiresDeviceIdle (boolean requiresDeviceIdle)

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.

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.

Returns
JobInfo.Builder

setRequiresStorageNotLow

added in API level 26
public JobInfo.Builder setRequiresStorageNotLow (boolean storageNotLow)

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.

Returns
JobInfo.Builder

setTransientExtras

added in API level 26
public JobInfo.Builder setTransientExtras (Bundle extras)

Set optional transient extras.

Because setting this property is not compatible with persisted jobs, doing so will throw an IllegalArgumentException when build() is called.

Parameters
extras Bundle: Bundle containing extras you want the scheduler to hold on to for you.

This value must never be null.

Returns
JobInfo.Builder

setTriggerContentMaxDelay

added in API level 24
public JobInfo.Builder setTriggerContentMaxDelay (long durationMs)

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.

Returns
JobInfo.Builder

setTriggerContentUpdateDelay

added in API level 24
public JobInfo.Builder setTriggerContentUpdateDelay (long durationMs)

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.

Returns
JobInfo.Builder