# Print output for @column tags ?> JobParameters - Android SDK | Android Developers

Most visited

Recently visited

JobParameters

public class JobParameters
extends Object implements Parcelable

java.lang.Object
   ↳ android.app.job.JobParameters


Contains the parameters used to configure/identify your job. You do not create this object yourself, instead it is handed in to your application by the System.

Summary

Inherited constants

Fields

public static final Creator<JobParameters> CREATOR

Public methods

void completeWork(JobWorkItem work)

Report the completion of executing a JobWorkItem previously returned by dequeueWork().

JobWorkItem dequeueWork()

Dequeue the next pending JobWorkItem from these JobParameters associated with their currently running job.

int describeContents()

Describe the kinds of special objects contained in this Parcelable instance's marshaled representation.

ClipData getClipData()
int getClipGrantFlags()
PersistableBundle getExtras()
int getJobId()
Network getNetwork()

Return the network that should be used to perform any network requests for this job.

Bundle getTransientExtras()
String[] getTriggeredContentAuthorities()

For jobs with JobInfo.Builder.addTriggerContentUri(JobInfo.TriggerContentUri) set, this reports which content authorities have triggered the job.

Uri[] getTriggeredContentUris()

For jobs with JobInfo.Builder.addTriggerContentUri(JobInfo.TriggerContentUri) set, this reports which URIs have triggered the job.

boolean isOverrideDeadlineExpired()

For jobs with JobInfo.Builder.setOverrideDeadline(long) set, this provides an easy way to tell whether the job is being executed due to the deadline expiring.

void writeToParcel(Parcel dest, int flags)

Flatten this object in to a Parcel.

Inherited methods

Fields

CREATOR

public static final Creator<JobParameters> CREATOR

Public methods

completeWork

public void completeWork (JobWorkItem work)

Report the completion of executing a JobWorkItem previously returned by dequeueWork(). This tells the system you are done with the work associated with that item, so it will not be returned again. Note that if this is the last work in the queue, completing it here will not finish the overall job -- for that to happen, you still need to call dequeueWork() again.

If you are enqueueing work into a job, you must call this method for each piece of work you process. Do not call JobService#jobFinished(JobParameters, boolean) or else you can lose work in your queue.

Parameters
work JobWorkItem: The work you have completed processing, as previously returned by dequeueWork() This value cannot be null.

dequeueWork

public JobWorkItem dequeueWork ()

Dequeue the next pending JobWorkItem from these JobParameters associated with their currently running job. Calling this method when there is no more work available and all previously dequeued work has been completed will result in the system taking care of stopping the job for you -- you should not call JobService#jobFinished(JobParameters, boolean) yourself (otherwise you risk losing an upcoming JobWorkItem that is being enqueued at the same time).

Once you are done with the JobWorkItem returned by this method, you must call completeWork(android.app.job.JobWorkItem) with it to inform the system that you are done executing the work. The job will not be finished until all dequeued work has been completed. You do not, however, have to complete each returned work item before deqeueing the next one -- you can use dequeueWork() multiple times before completing previous work if you want to process work in parallel, and you can complete the work in whatever order you want.

If the job runs to the end of its available time period before all work has been completed, it will stop as normal. You should return true from JobService#onStopJob(JobParameters) in order to have the job rescheduled, and by doing so any pending as well as remaining uncompleted work will be re-queued for the next time the job runs.

This example shows how to construct a JobService that will serially dequeue and process work that is available for it:

public class JobWorkService extends JobService {
    private NotificationManager mNM;
    private CommandProcessor mCurProcessor;

    /**
     * This is a task to dequeue and process work in the background.
     */
    final class CommandProcessor extends AsyncTask<Void, Void, Void> {
        private final JobParameters mParams;

        CommandProcessor(JobParameters params) {
            mParams = params;
        }

        @Override
        protected Void doInBackground(Void... params) {
            boolean cancelled;
            JobWorkItem work;

            /**
             * Iterate over available work.  Once dequeueWork() returns null, the
             * job's work queue is empty and the job has stopped, so we can let this
             * async task complete.
             */
            while (!(cancelled=isCancelled()) && (work=mParams.dequeueWork()) != null) {
                String txt = work.getIntent().getStringExtra("name");
                Log.i("JobWorkService", "Processing work: " + work + ", msg: " + txt);
                showNotification(txt);

                // Process work here...  we'll pretend by sleeping.
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }

                hideNotification();

                // Tell system we have finished processing the work.
                Log.i("JobWorkService", "Done with: " + work);
                mParams.completeWork(work);
            }

            if (cancelled) {
                Log.i("JobWorkService", "CANCELLED!");
            }

            return null;
        }
    }

    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Toast.makeText(this, R.string.service_created, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        hideNotification();
        Toast.makeText(this, R.string.service_destroyed, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        // Start task to pull work out of the queue and process it.
        mCurProcessor = new CommandProcessor(params);
        mCurProcessor.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        // Allow the job to continue running while we process work.
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        // Have the processor cancel its current work.
        mCurProcessor.cancel(true);

        // Tell the system to reschedule the job -- the only reason we would be here is
        // because the job needs to stop for some reason before it has completed all of
        // its work, so we would like it to remain to finish that work in the future.
        return true;
    }

    /**
     * Show a notification while this service is running.
     */
    private void showNotification(String text) {
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, JobWorkServiceActivity.class), 0);

        // Set the info for the views that show in the notification panel.
        Notification.Builder noteBuilder = new Notification.Builder(this)
                .setSmallIcon(R.drawable.stat_sample)  // the status icon
                .setTicker(text)  // the status text
                .setWhen(System.currentTimeMillis())  // the time stamp
                .setContentTitle(getText(R.string.service_start_arguments_label))  // the label
                .setContentText(text)  // the contents of the entry
                .setContentIntent(contentIntent);  // The intent to send when the entry is clicked

        // We show this for as long as our service is processing a command.
        noteBuilder.setOngoing(true);

        // Send the notification.
        // We use a string id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.string.job_service_created, noteBuilder.build());
    }

    private void hideNotification() {
        mNM.cancel(R.string.service_created);
    }
}

Returns
JobWorkItem Returns a new JobWorkItem if there is one pending, otherwise null. If null is returned, the system will also stop the job if all work has also been completed. (This means that for correct operation, you must always call dequeueWork() after you have completed other work, to check either for more work or allow the system to stop the job.)

describeContents

public int describeContents ()

Describe the kinds of special objects contained in this Parcelable instance's marshaled representation. For example, if the object will include a file descriptor in the output of writeToParcel(android.os.Parcel, int), the return value of this method must include the CONTENTS_FILE_DESCRIPTOR bit.

Returns
int a bitmask indicating the set of special object types marshaled by this Parcelable object instance. Value is either 0 or CONTENTS_FILE_DESCRIPTOR

getClipData

public ClipData getClipData ()

Returns
ClipData The clip you passed in when constructing this job with JobInfo.Builder.setClipData(ClipData, int). Will be null if it was not set.

getClipGrantFlags

public int getClipGrantFlags ()

Returns
int The clip grant flags you passed in when constructing this job with JobInfo.Builder.setClipData(ClipData, int). Will be 0 if it was not set.

getExtras

public PersistableBundle getExtras ()

Returns
PersistableBundle The extras you passed in when constructing this job with JobInfo.Builder.setExtras(android.os.PersistableBundle). This will never be null. If you did not set any extras this will be an empty bundle.

getJobId

public int getJobId ()

Returns
int The unique id of this job, specified at creation time.

getNetwork

public Network getNetwork ()

Return the network that should be used to perform any network requests for this job.

Devices may have multiple active network connections simultaneously, or they may not have a default network route at all. To correctly handle all situations like this, your job should always use the network returned by this method instead of implicitly using the default network route.

Note that the system may relax the 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.

Returns
Network the network that should be used to perform any network requests for this job, or null if this job didn't set any required network type.

See also:

getTransientExtras

public Bundle getTransientExtras ()

Returns
Bundle The transient extras you passed in when constructing this job with JobInfo.Builder.setTransientExtras(android.os.Bundle). This will never be null. If you did not set any extras this will be an empty bundle.

getTriggeredContentAuthorities

public String[] getTriggeredContentAuthorities ()

For jobs with JobInfo.Builder.addTriggerContentUri(JobInfo.TriggerContentUri) set, this reports which content authorities have triggered the job. It will only be null if no authorities have triggered it -- that is, the job executed for some other reason, such as a deadline expiring. If this is non-null, you can use getTriggeredContentUris() to retrieve the details of which URIs changed (as long as that has not exceeded the maximum number it can reported).

Returns
String[]

getTriggeredContentUris

public Uri[] getTriggeredContentUris ()

For jobs with JobInfo.Builder.addTriggerContentUri(JobInfo.TriggerContentUri) set, this reports which URIs have triggered the job. This will be null if either no URIs have triggered it (it went off due to a deadline or other reason), or the number of changed URIs is too large to report. Whether or not the number of URIs is too large, you can always use getTriggeredContentAuthorities() to determine whether the job was triggered due to any content changes and the authorities they are associated with.

Returns
Uri[]

isOverrideDeadlineExpired

public boolean isOverrideDeadlineExpired ()

For jobs with JobInfo.Builder.setOverrideDeadline(long) set, this provides an easy way to tell whether the job is being executed due to the deadline expiring. Note: If the job is running because its deadline expired, it implies that its constraints will not be met.

Returns
boolean

writeToParcel

public void writeToParcel (Parcel dest, 
                int flags)

Flatten this object in to a Parcel.

Parameters
dest Parcel: The Parcel in which the object should be written.

flags int: Additional flags about how the object should be written. May be 0 or Parcelable.PARCELABLE_WRITE_RETURN_VALUE. Value is either 0 or a combination of Parcelable.PARCELABLE_WRITE_RETURN_VALUE, and android.os.Parcelable.PARCELABLE_ELIDE_DUPLICATES