Skip to content

Most visited

Recently visited

navigation

JobIntentService

public abstract class JobIntentService
extends Service

java.lang.Object
   ↳ android.content.Context
     ↳ android.content.ContextWrapper
       ↳ android.app.Service
         ↳ android.support.v4.app.JobIntentService


Helper for processing work that has been enqueued for a job/service. When running on Android O or later, the work will be dispatched as a job via JobScheduler.enqueue. When running on older versions of the platform, it will use Context.startService.

You must publish your subclass in your manifest for the system to interact with. This should be published as a JobService, as described for that class, since on O and later platforms it will be executed that way.

Use enqueueWork(Context, Class, int, Intent) to enqueue new work to be dispatched to and handled by your service. It will be executed in onHandleWork(Intent).

You do not need to use WakefulBroadcastReceiver when using this class. When running on Android O, the JobScheduler will take care of wake locks for you (holding a wake lock from the time you enqueue work until the job has been dispatched and while it is running). When running on previous versions of the platform, this wake lock handling is emulated in the class here by directly calling the PowerManager; this means the application must request the WAKE_LOCK permission.

There are a few important differences in behavior when running on Android O or later as a Job vs. pre-O:

  • When running as a pre-O service, the act of enqueueing work will generally start the service immediately, regardless of whether the device is dozing or in other conditions. When running as a Job, it will be subject to standard JobScheduler policies for a Job with a setOverrideDeadline(long) of 0: the job will not run while the device is dozing, it may get delayed more than a service if the device is under strong memory pressure with lots of demand to run jobs.

  • When running as a pre-O service, the normal service execution semantics apply: the service can run indefinitely, though the longer it runs the more likely the system will be to outright kill its process, and under memory pressure one should expect the process to be killed even of recently started services. When running as a Job, the typical JobService execution time limit will apply, after which the job will be stopped (cleanly, not by killing the process) and rescheduled to continue its execution later. Job are generally not killed when the system is under memory pressure, since the number of concurrent jobs is adjusted based on the memory state of the device.

Here is an example implementation of this class:

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.JobIntentService;
import android.util.Log;
import android.widget.Toast;

/**
 * Example implementation of a JobIntentService.
 */
public class SimpleJobIntentService extends JobIntentService {
    /**
     * Unique job ID for this service.
     */
    static final int JOB_ID = 1000;

    /**
     * Convenience method for enqueuing work in to this service.
     */
    static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, SimpleJobIntentService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(Intent intent) {
        // We have received work to do.  The system or framework is already
        // holding a wake lock for us at this point, so we can just go.
        Log.i("SimpleJobIntentService", "Executing work: " + intent);
        String label = intent.getStringExtra("label");
        if (label == null) {
            label = intent.toString();
        }
        toast("Executing: " + label);
        for (int i = 0; i < 5; i++) {
            Log.i("SimpleJobIntentService", "Running service " + (i + 1)
                    + "/5 @ " + SystemClock.elapsedRealtime());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
        Log.i("SimpleJobIntentService", "Completed service @ " + SystemClock.elapsedRealtime());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        toast("All work complete");
    }

    final Handler mHandler = new Handler();

    // Helper for showing tests
    void toast(final CharSequence text) {
        mHandler.post(new Runnable() {
            @Override public void run() {
                Toast.makeText(SimpleJobIntentService.this, text, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Summary

Inherited constants

From class android.app.Service
From class android.content.Context
From interface android.content.ComponentCallbacks2

Public constructors

JobIntentService()

Default empty constructor.

Public methods

static void enqueueWork(Context context, ComponentName component, int jobId, Intent work)

Like enqueueWork(Context, Class, int, Intent), but supplies a ComponentName for the service to interact with instead of its class.

static void enqueueWork(Context context, Class cls, int jobId, Intent work)

Call this to enqueue work for your subclass of JobIntentService.

boolean isStopped()

Returns true if onStopCurrentWork() has been called.

IBinder onBind(Intent intent)

Returns the IBinder for the JobServiceEngine when running as a JobService on O and later platforms.

void onCreate()

Called by the system when the service is first created.

void onDestroy()

Called by the system to notify a Service that it is no longer used and is being removed.

int onStartCommand(Intent intent, int flags, int startId)

Processes start commands when running as a pre-O service, enqueueing them to be later dispatched in onHandleWork(Intent).

boolean onStopCurrentWork()

This will be called if the JobScheduler has decided to stop this job.

void setInterruptIfStopped(boolean interruptIfStopped)

Control whether code executing in onHandleWork(Intent) will be interrupted if the job is stopped.

Protected methods

abstract void onHandleWork(Intent intent)

Called serially for each work dispatched to and processed by the service.

Inherited methods

From class android.app.Service
From class android.content.ContextWrapper
From class android.content.Context
From class java.lang.Object
From interface android.content.ComponentCallbacks2
From interface android.content.ComponentCallbacks

Public constructors

JobIntentService

added in version 26.0.0
JobIntentService ()

Default empty constructor.

Public methods

enqueueWork

added in version 26.0.0
void enqueueWork (Context context, 
                ComponentName component, 
                int jobId, 
                Intent work)

Like enqueueWork(Context, Class, int, Intent), but supplies a ComponentName for the service to interact with instead of its class.

Parameters
context Context: Context this is being called from.

component ComponentName: The published ComponentName of the class this work should be dispatched to.

jobId int: A unique job ID for scheduling; must be the same value for all work enqueued for the same class.

work Intent: The Intent of work to enqueue.

enqueueWork

added in version 26.0.0
void enqueueWork (Context context, 
                Class cls, 
                int jobId, 
                Intent work)

Call this to enqueue work for your subclass of JobIntentService. This will either directly start the service (when running on pre-O platforms) or enqueue work for it as a job (when running on O and later). In either case, a wake lock will be held for you to ensure you continue running. The work you enqueue will ultimately appear at onHandleWork(Intent).

Parameters
context Context: Context this is being called from.

cls Class: The concrete class the work should be dispatched to (this is the class that is published in your manifest).

jobId int: A unique job ID for scheduling; must be the same value for all work enqueued for the same class.

work Intent: The Intent of work to enqueue.

isStopped

added in version 26.0.0
boolean isStopped ()

Returns true if onStopCurrentWork() has been called. You can use this, while executing your work, to see if it should be stopped.

Returns
boolean

onBind

added in version 26.0.0
IBinder onBind (Intent intent)

Returns the IBinder for the JobServiceEngine when running as a JobService on O and later platforms.

Parameters
intent Intent: The Intent that was used to bind to this service, as given to Context.bindService. Note that any extras that were included with the Intent at that point will not be seen here.

Returns
IBinder Return an IBinder through which clients can call on to the service.

onCreate

void onCreate ()

Called by the system when the service is first created. Do not call this method directly.

onDestroy

void onDestroy ()

Called by the system to notify a Service that it is no longer used and is being removed. The service should clean up any resources it holds (threads, registered receivers, etc) at this point. Upon return, there will be no more calls in to this Service object and it is effectively dead. Do not call this method directly.

onStartCommand

int onStartCommand (Intent intent, 
                int flags, 
                int startId)

Processes start commands when running as a pre-O service, enqueueing them to be later dispatched in onHandleWork(Intent).

Parameters
intent Intent: The Intent supplied to startService(Intent), as given. This may be null if the service is being restarted after its process has gone away, and it had previously returned anything except START_STICKY_COMPATIBILITY.

flags int: Additional data about this start request.

startId int: A unique integer representing this specific request to start. Use with stopSelfResult(int).

Returns
int The return value indicates what semantics the system should use for the service's current started state. It may be one of the constants associated with the START_CONTINUATION_MASK bits.

onStopCurrentWork

added in version 26.0.0
boolean onStopCurrentWork ()

This will be called if the JobScheduler has decided to stop this job. The job for this service does not have any constraints specified, so this will only generally happen if the service exceeds the job's maximum execution time.

Returns
boolean True to indicate to the JobManager whether you'd like to reschedule this work, false to drop this and all following work. Regardless of the value returned, your service must stop executing or the system will ultimately kill it. The default implementation returns true, and that is most likely what you want to return as well (so no work gets lost).

setInterruptIfStopped

added in version 26.0.0
void setInterruptIfStopped (boolean interruptIfStopped)

Control whether code executing in onHandleWork(Intent) will be interrupted if the job is stopped. By default this is false. If called and set to true, any time onStopCurrentWork() is called, the class will first call AsyncTask.cancel(true) to interrupt the running task.

Parameters
interruptIfStopped boolean: Set to true to allow the system to interrupt actively running work.

Protected methods

onHandleWork

added in version 26.0.0
void onHandleWork (Intent intent)

Called serially for each work dispatched to and processed by the service. This method is called on a background thread, so you can do long blocking operations here. Upon returning, that work will be considered complete and either the next pending work dispatched here or the overall service destroyed now that it has nothing else to do.

Be aware that when running as a job, you are limited by the maximum job execution time and any single or total sequential items of work that exceeds that limit will cause the service to be stopped while in progress and later restarted with the last unfinished work. (There is currently no limit on execution duration when running as a pre-O plain Service.)

Parameters
intent Intent: The intent describing the work to now be processed.

This site uses cookies to store your preferences for site-specific language and display options.

Get the latest Android developer news and tips that will help you find success on Google Play.

* Required Fields

Hooray!

Browse this site in ?

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

Take a short survey?
Help us improve the Android developer experience.
(Sep 2017 survey)