JobIntentService

Added in 1.1.0
Deprecated in 1.6.0

public abstract class JobIntentService extends Service


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 android.app.job.JobService, as described for that class, since on O and later platforms it will be executed that way.

Use enqueueWork to enqueue new work to be dispatched to and handled by your service. It will be executed in onHandleWork.

You do not need to use androidx.legacy.content.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 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 android.app.job.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.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;

/**
 * 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(@NonNull 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");
    }

    @SuppressWarnings("deprecation")
    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

Public constructors

Default empty constructor.

Public methods

static void
enqueueWork(
    @NonNull Context context,
    @NonNull Class<Object> cls,
    int jobId,
    @NonNull Intent work
)

Call this to enqueue work for your subclass of JobIntentService.

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

Like enqueueWork, but supplies a ComponentName for the service to interact with instead of its class.

boolean

Returns true if onStopCurrentWork has been called.

IBinder

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

void
void
int
onStartCommand(@Nullable Intent intent, int flags, int startId)

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

boolean

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

void
setInterruptIfStopped(boolean interruptIfStopped)

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

Protected methods

abstract void

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

Inherited Constants

From android.content.ComponentCallbacks2
static final int
static final int
static final int
static final int
static final int
static final int
static final int
From android.content.Context
static final String
ACCESSIBILITY_SERVICE = "accessibility"
static final String
ACCOUNT_SERVICE = "account"
static final String
ACTIVITY_SERVICE = "activity"
static final String
ALARM_SERVICE = "alarm"
static final String
APPWIDGET_SERVICE = "appwidget"
static final String
APP_OPS_SERVICE = "appops"
static final String
APP_SEARCH_SERVICE = "app_search"
static final String
AUDIO_SERVICE = "audio"
static final String
BATTERY_SERVICE = "batterymanager"
static final int
static final int
static final int
static final int
static final int
static final int
static final int
BIND_EXTERNAL_SERVICE = -2147483648
static final long
BIND_EXTERNAL_SERVICE_LONG = 4611686018427387904
static final int
static final int
static final int
static final int
static final int
static final int
static final String
BIOMETRIC_SERVICE = "biometric"
static final String
BLOB_STORE_SERVICE = "blob_store"
static final String
BLUETOOTH_SERVICE = "bluetooth"
static final String
BUGREPORT_SERVICE = "bugreport"
static final String
CAMERA_SERVICE = "camera"
static final String
CAPTIONING_SERVICE = "captioning"
static final String
CARRIER_CONFIG_SERVICE = "carrier_config"
static final String
CLIPBOARD_SERVICE = "clipboard"
static final String
COMPANION_DEVICE_SERVICE = "companiondevice"
static final String
CONNECTIVITY_DIAGNOSTICS_SERVICE = "connectivity_diagnostics"
static final String
CONNECTIVITY_SERVICE = "connectivity"
static final String
CONSUMER_IR_SERVICE = "consumer_ir"
static final int
static final int
static final int
static final String
CREDENTIAL_SERVICE = "credential"
static final String
CROSS_PROFILE_APPS_SERVICE = "crossprofileapps"
static final int
static final int
static final String
DEVICE_LOCK_SERVICE = "device_lock"
static final String
DEVICE_POLICY_SERVICE = "device_policy"
static final String
DISPLAY_HASH_SERVICE = "display_hash"
static final String
DISPLAY_SERVICE = "display"
static final String
DOMAIN_VERIFICATION_SERVICE = "domain_verification"
static final String
DOWNLOAD_SERVICE = "download"
static final String
DROPBOX_SERVICE = "dropbox"
static final String
EUICC_SERVICE = "euicc"
static final String
FILE_INTEGRITY_SERVICE = "file_integrity"
static final String
FINGERPRINT_SERVICE = "fingerprint"
static final String
GAME_SERVICE = "game"
static final String
GRAMMATICAL_INFLECTION_SERVICE = "grammatical_inflection"
static final String
HARDWARE_PROPERTIES_SERVICE = "hardware_properties"
static final String
HEALTHCONNECT_SERVICE = "healthconnect"
static final String
INPUT_METHOD_SERVICE = "input_method"
static final String
INPUT_SERVICE = "input"
static final String
IPSEC_SERVICE = "ipsec"
static final String
JOB_SCHEDULER_SERVICE = "jobscheduler"
static final String
KEYGUARD_SERVICE = "keyguard"
static final String
LAUNCHER_APPS_SERVICE = "launcherapps"
static final String
LAYOUT_INFLATER_SERVICE = "layout_inflater"
static final String
LOCALE_SERVICE = "locale"
static final String
LOCATION_SERVICE = "location"
static final String
MEDIA_COMMUNICATION_SERVICE = "media_communication"
static final String
MEDIA_METRICS_SERVICE = "media_metrics"
static final String
MEDIA_PROJECTION_SERVICE = "media_projection"
static final String
MEDIA_ROUTER_SERVICE = "media_router"
static final String
MEDIA_SESSION_SERVICE = "media_session"
static final String
MIDI_SERVICE = "midi"
static final int
MODE_APPEND = 32768
static final int
static final int

This field is deprecated.

static final int
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final String
static final String
NFC_SERVICE = "nfc"
static final String
NOTIFICATION_SERVICE = "notification"
static final String
NSD_SERVICE = "servicediscovery"
static final String
OVERLAY_SERVICE = "overlay"
static final String
PEOPLE_SERVICE = "people"
static final String
PERFORMANCE_HINT_SERVICE = "performance_hint"
static final String
POWER_SERVICE = "power"
static final String
PRINT_SERVICE = "print"
static final int
static final int
static final int
static final String
RESTRICTIONS_SERVICE = "restrictions"
static final String
ROLE_SERVICE = "role"
static final String
SEARCH_SERVICE = "search"
static final String
SENSOR_SERVICE = "sensor"
static final String
SHORTCUT_SERVICE = "shortcut"
static final String
STATUS_BAR_SERVICE = "statusbar"
static final String
STORAGE_SERVICE = "storage"
static final String
STORAGE_STATS_SERVICE = "storagestats"
static final String
SYSTEM_HEALTH_SERVICE = "systemhealth"
static final String
TELECOM_SERVICE = "telecom"
static final String
TELEPHONY_IMS_SERVICE = "telephony_ims"
static final String
static final String
TELEPHONY_SUBSCRIPTION_SERVICE = "telephony_subscription_service"
static final String
TEXT_CLASSIFICATION_SERVICE = "textclassification"
static final String
static final String
TV_INPUT_SERVICE = "tv_input"
static final String
TV_INTERACTIVE_APP_SERVICE = "tv_interactive_app"
static final String
UI_MODE_SERVICE = "uimode"
static final String
USAGE_STATS_SERVICE = "usagestats"
static final String
USB_SERVICE = "usb"
static final String
USER_SERVICE = "user"
static final String
VIBRATOR_MANAGER_SERVICE = "vibrator_manager"
static final String
VIBRATOR_SERVICE = "vibrator"

This field is deprecated.

static final String
VIRTUAL_DEVICE_SERVICE = "virtualdevice"
static final String
VPN_MANAGEMENT_SERVICE = "vpn_management"
static final String
WALLPAPER_SERVICE = "wallpaper"
static final String
WIFI_AWARE_SERVICE = "wifiaware"
static final String
WIFI_P2P_SERVICE = "wifip2p"
static final String
static final String
WIFI_SERVICE = "wifi"
static final String
WINDOW_SERVICE = "window"
From android.app.Service
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int

This field is deprecated.

static final int

Inherited methods

From android.content.Context
final int
getColor(int id)
final ColorStateList
final Drawable
getDrawable(int id)
final String
getString(int resId)
final T
<T> getSystemService(Class<T> serviceClass)
final CharSequence
getText(int resId)
final TypedArray
void
void
sendBroadcastWithMultiplePermissions(
    Intent intent,
    String[] receiverPermissions
)
From android.content.ContextWrapper
boolean
bindIsolatedService(
    Intent service,
    int flags,
    String instanceName,
    Executor executor,
    ServiceConnection conn
)
boolean
bindService(Intent service, ServiceConnection conn, int flags)
boolean
bindServiceAsUser(
    Intent service,
    ServiceConnection conn,
    int flags,
    UserHandle user
)
int
int
checkCallingOrSelfUriPermission(Uri uri, int modeFlags)
int[]
checkCallingOrSelfUriPermissions(List<Uri> uris, int modeFlags)
int
int
checkCallingUriPermission(Uri uri, int modeFlags)
int[]
checkCallingUriPermissions(List<Uri> uris, int modeFlags)
int
checkPermission(String permission, int pid, int uid)
int
int
checkUriPermission(Uri uri, int pid, int uid, int modeFlags)
int[]
checkUriPermissions(List<Uri> uris, int pid, int uid, int modeFlags)
void

This method is deprecated.

Context
Context
Context
Context
Context
createDeviceContext(int deviceId)
Context
Context
Context
createPackageContext(String packageName, int flags)
Context
createWindowContext(int type, Bundle options)
String[]
boolean
boolean
boolean
void
void
enforceCallingOrSelfUriPermission(
    Uri uri,
    int modeFlags,
    String message
)
void
enforceCallingPermission(String permission, String message)
void
enforceCallingUriPermission(Uri uri, int modeFlags, String message)
void
enforcePermission(String permission, int pid, int uid, String message)
void
enforceUriPermission(
    Uri uri,
    int pid,
    int uid,
    int modeFlags,
    String message
)
String[]
Context
ApplicationInfo
AssetManager
AttributionSource
String
Context
File
ClassLoader
File
ContentResolver
File
File
int
File
getDir(String name, int mode)
Display
File
File[]
File
File[]
File[]

This method is deprecated.

File
File
Executor
Looper
File
File
File[]
String
String
PackageManager
String
String
ContextParams
Resources
SharedPreferences
getSharedPreferences(String name, int mode)
Object
String
Resources.Theme
Drawable

This method is deprecated.

int

This method is deprecated.

int

This method is deprecated.

void
grantUriPermission(String toPackage, Uri uri, int modeFlags)
boolean
boolean
boolean
boolean
moveDatabaseFrom(Context sourceContext, String name)
boolean
moveSharedPreferencesFrom(Context sourceContext, String name)
FileInputStream
FileOutputStream
openFileOutput(String name, int mode)
SQLiteDatabase
openOrCreateDatabase(
    String name,
    int mode,
    SQLiteDatabase.CursorFactory factory
)
Drawable

This method is deprecated.

void
void
Intent
void

This method is deprecated.

void

This method is deprecated.

void
void
revokeUriPermission(Uri uri, int modeFlags)
void
void
void
sendOrderedBroadcast(Intent intent, String receiverPermission)
void
sendOrderedBroadcastAsUser(
    Intent intent,
    UserHandle user,
    String receiverPermission,
    BroadcastReceiver resultReceiver,
    Handler scheduler,
    int initialCode,
    String initialData,
    Bundle initialExtras
)
void

This method is deprecated.

void

This method is deprecated.

void
sendStickyOrderedBroadcast(
    Intent intent,
    BroadcastReceiver resultReceiver,
    Handler scheduler,
    int initialCode,
    String initialData,
    Bundle initialExtras
)

This method is deprecated.

void
sendStickyOrderedBroadcastAsUser(
    Intent intent,
    UserHandle user,
    BroadcastReceiver resultReceiver,
    Handler scheduler,
    int initialCode,
    String initialData,
    Bundle initialExtras
)

This method is deprecated.

void
setTheme(int resid)
void

This method is deprecated.

void
startActivities(Intent[] intents)
void
ComponentName
boolean
startInstrumentation(
    ComponentName className,
    String profileFile,
    Bundle arguments
)
void
startIntentSender(
    IntentSender intent,
    Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags
)
ComponentName
boolean
void
void
void
void
void
updateServiceGroup(ServiceConnection conn, int group, int importance)
From android.app.Service
void
void
dump(FileDescriptor fd, PrintWriter writer, String[] args)
final Application
final int
void
void
void
onRebind(Intent intent)
void
onStart(Intent intent, int startId)

This method is deprecated.

void
onTaskRemoved(Intent rootIntent)
void
onTimeout(int startId)
void
onTrimMemory(int level)
boolean
onUnbind(Intent intent)
final void
startForeground(int id, Notification notification)
final void
stopForeground(boolean removeNotification)

This method is deprecated.

final void
final boolean
stopSelfResult(int startId)

Public constructors

JobIntentService

Added in 1.1.0
Deprecated in 1.6.0
public JobIntentService()

Default empty constructor.

Public methods

enqueueWork

Added in 1.2.0
Deprecated in 1.6.0
public static void enqueueWork(
    @NonNull Context context,
    @NonNull Class<Object> cls,
    int jobId,
    @NonNull 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.

Parameters
@NonNull Context context

Context this is being called from.

@NonNull Class<Object> cls

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

int jobId

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

@NonNull Intent work

The Intent of work to enqueue.

enqueueWork

Added in 1.1.0
Deprecated in 1.6.0
public static void enqueueWork(
    @NonNull Context context,
    @NonNull ComponentName component,
    int jobId,
    @NonNull Intent work
)

Like enqueueWork, but supplies a ComponentName for the service to interact with instead of its class.

Parameters
@NonNull Context context

Context this is being called from.

@NonNull ComponentName component

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

int jobId

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

@NonNull Intent work

The Intent of work to enqueue.

isStopped

Added in 1.1.0
Deprecated in 1.6.0
public boolean isStopped()

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

onBind

Added in 1.1.0
Deprecated in 1.6.0
public IBinder onBind(@NonNull Intent intent)

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

onCreate

public void onCreate()

onDestroy

public void onDestroy()

onStartCommand

public int onStartCommand(@Nullable Intent intent, int flags, int startId)

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

onStopCurrentWork

Added in 1.1.0
Deprecated in 1.6.0
public 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 1.1.0
Deprecated in 1.6.0
public void setInterruptIfStopped(boolean interruptIfStopped)

Control whether code executing in onHandleWork 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
boolean interruptIfStopped

Set to true to allow the system to interrupt actively running work.

Protected methods

onHandleWork

Added in 1.1.0
Deprecated in 1.6.0
protected abstract void onHandleWork(@NonNull 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
@NonNull Intent intent

The intent describing the work to now be processed.