Added in API level 21

JobService

abstract class JobService : Service
kotlin.Any
   ↳ android.content.Context
   ↳ android.content.ContextWrapper
   ↳ android.app.Service
   ↳ android.app.job.JobService

Entry point for the callback from the android.app.job.JobScheduler.

This is the base class that handles asynchronous requests that were previously scheduled. You are responsible for overriding JobService#onStartJob(JobParameters), which is where you will implement your job logic.

This service executes each incoming job on a android.os.Handler running on your application's main thread. This means that you must offload your execution logic to another thread/handler/android.os.AsyncTask of your choosing. Not doing so will result in blocking any future callbacks from the JobScheduler - specifically onStopJob(android.app.job.JobParameters), which is meant to inform you that the scheduling requirements are no longer being met.

Since the introduction of JobScheduler, if an app did not return from onStartJob(android.app.job.JobParameters) within several seconds, JobScheduler would consider the app unresponsive and clean up job execution. In such cases, the app was no longer considered to be running a job and therefore did not have any of the job lifecycle guarantees outlined in JobScheduler. However, prior to Android version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, the failure and cleanup were silent and apps had no indication that they no longer had job lifecycle guarantees. Starting with Android version android.os.Build.VERSION_CODES#UPSIDE_DOWN_CAKE, JobScheduler will explicitly trigger an ANR in such cases so that apps and developers can be aware of the issue. Similar behavior applies to the return time from onStopJob(android.app.job.JobParameters) as well.

If you see ANRs, then the app may be doing too much work on the UI thread. Ensure that potentially long operations are moved to a worker thread.

As a subclass of Service, there will only be one active instance of any JobService subclasses, regardless of job ID. This means that if you schedule multiple jobs with different job IDs but using the same JobService class, that JobService may receive multiple calls to onStartJob(android.app.job.JobParameters) and onStopJob(android.app.job.JobParameters), with each call being for the separate jobs.

Summary

Constants
static Int

Detach the notification supplied to setNotification(android.app.job.JobParameters,int,android.app.Notification,int) when the job ends.

static Int

Cancel and remove the notification supplied to setNotification(android.app.job.JobParameters,int,android.app.Notification,int) when the job ends.

static String

Job services must be protected with this permission:

<service android:name="MyJobService"
               android:permission="android.permission.BIND_JOB_SERVICE" >
          ...
      </service>
  

Inherited constants
Public constructors

Public methods
Unit
jobFinished(params: JobParameters!, wantsReschedule: Boolean)

Call this to inform the JobScheduler that the job has finished its work.

open Unit

This method is called that for a job that has a network constraint when the network to be used by the job changes.

abstract Boolean

Called to indicate that the job has begun executing.

abstract Boolean

This method is called if the system has determined that you must stop execution of your job even before you've had a chance to call jobFinished(android.app.job.JobParameters,boolean).

Unit
setNotification(params: JobParameters, notificationId: Int, notification: Notification, jobEndNotificationPolicy: Int)

Provide JobScheduler with a notification to post and tie to this job's lifecycle.

Unit
updateEstimatedNetworkBytes(params: JobParameters, downloadBytes: Long, uploadBytes: Long)

Update the amount of data this job is estimated to transfer after the job has started.

Unit
updateEstimatedNetworkBytes(params: JobParameters, jobWorkItem: JobWorkItem, downloadBytes: Long, uploadBytes: Long)

Update the amount of data this JobWorkItem is estimated to transfer after the job has started.

Unit
updateTransferredNetworkBytes(params: JobParameters, transferredDownloadBytes: Long, transferredUploadBytes: Long)

Tell JobScheduler how much data has successfully been transferred for the data transfer job.

Unit
updateTransferredNetworkBytes(params: JobParameters, item: JobWorkItem, transferredDownloadBytes: Long, transferredUploadBytes: Long)

Tell JobScheduler how much data has been transferred for the data transfer JobWorkItem.

Inherited functions

Constants

JOB_END_NOTIFICATION_POLICY_DETACH

Added in API level 34
static val JOB_END_NOTIFICATION_POLICY_DETACH: Int

Detach the notification supplied to setNotification(android.app.job.JobParameters,int,android.app.Notification,int) when the job ends. The notification will remain shown even after JobScheduler stops the job.

Value: 0

JOB_END_NOTIFICATION_POLICY_REMOVE

Added in API level 34
static val JOB_END_NOTIFICATION_POLICY_REMOVE: Int

Cancel and remove the notification supplied to setNotification(android.app.job.JobParameters,int,android.app.Notification,int) when the job ends. The notification will be removed from the notification shade.

Value: 1

PERMISSION_BIND

Added in API level 21
static val PERMISSION_BIND: String

Job services must be protected with this permission:

<service android:name="MyJobService"
               android:permission="android.permission.BIND_JOB_SERVICE" >
          ...
      </service>
  

If a job service is declared in the manifest but not protected with this permission, that service will be ignored by the system.

Value: "android.permission.BIND_JOB_SERVICE"

Public constructors

JobService

JobService()

Public methods

jobFinished

Added in API level 21
fun jobFinished(
    params: JobParameters!,
    wantsReschedule: Boolean
): Unit

Call this to inform the JobScheduler that the job has finished its work. When the system receives this message, it releases the wakelock being held for the job. This does not need to be called if onStopJob(android.app.job.JobParameters) has been called.

You can request that the job be scheduled again by passing true as the wantsReschedule parameter. This will apply back-off policy for the job; this policy can be adjusted through the android.app.job.JobInfo.Builder#setBackoffCriteria(long, int) method when the job is originally scheduled. The job's initial requirements are preserved when jobs are rescheduled, regardless of backed-off policy.

A job running while the device is dozing will not be rescheduled with the normal back-off policy. Instead, the job will be re-added to the queue and executed again during a future idle maintenance window.

Any user-initiated job cannot be rescheduled when the user has asked to stop the app via a system provided affordance (such as the Task Manager). In such situations, the value of wantsReschedule is always treated as false.

Parameters
params JobParameters!: The parameters identifying this job, as supplied to the job in the onStartJob(android.app.job.JobParameters) callback.
wantsReschedule Boolean: true if this job should be rescheduled according to the back-off criteria specified when it was first scheduled; false otherwise. When false is returned for a periodic job, the job will be rescheduled according to its periodic policy.

onNetworkChanged

Added in API level 34
open fun onNetworkChanged(params: JobParameters): Unit

This method is called that for a job that has a network constraint when the network to be used by the job changes. The new network object will be available via JobParameters#getNetwork(). Any network that results in this method call will match the job's requested network constraints.

For example, if a device is on a metered mobile network and then connects to an unmetered WiFi network, and the job has indicated that both networks satisfy its network constraint, then this method will be called to notify the job of the new unmetered WiFi network.

Parameters
params JobParameters: The parameters identifying this job, similar to what was supplied to the job in the onStartJob(android.app.job.JobParameters) callback, but with an updated network. This value cannot be null.

onStartJob

Added in API level 21
abstract fun onStartJob(params: JobParameters!): Boolean

Called to indicate that the job has begun executing. Override this method with the logic for your job. Like all other component lifecycle callbacks, this method executes on your application's main thread.

Return true from this method if your job needs to continue running. If you do this, the job remains active until you call jobFinished(android.app.job.JobParameters,boolean) to tell the system that it has completed its work, or until the job's required constraints are no longer satisfied. For example, if the job was scheduled using setRequiresCharging(true), it will be immediately halted by the system if the user unplugs the device from power, the job's onStopJob(android.app.job.JobParameters) callback will be invoked, and the app will be expected to shut down all ongoing work connected with that job.

The system holds a wakelock on behalf of your app as long as your job is executing. This wakelock is acquired before this method is invoked, and is not released until either you call jobFinished(android.app.job.JobParameters,boolean), or after the system invokes onStopJob(android.app.job.JobParameters) to notify your job that it is being shut down prematurely.

Returning false from this method means your job is already finished. The system's wakelock for the job will be released, and onStopJob(android.app.job.JobParameters) will not be invoked.

Parameters
params JobParameters!: Parameters specifying info about this job, including the optional extras configured with JobInfo.Builder#setExtras(android.os.PersistableBundle). This object serves to identify this specific running job instance when calling jobFinished(android.app.job.JobParameters,boolean).
Return
Boolean true if your service will continue running, using a separate thread when appropriate. false means that this job has completed its work.

onStopJob

Added in API level 21
abstract fun onStopJob(params: JobParameters!): Boolean

This method is called if the system has determined that you must stop execution of your job even before you've had a chance to call jobFinished(android.app.job.JobParameters,boolean). Once this method is called, you no longer need to call jobFinished(android.app.job.JobParameters,boolean).

This may happen if the requirements specified at schedule time are no longer met. For example you may have requested WiFi with android.app.job.JobInfo.Builder#setRequiredNetworkType(int), yet while your job was executing the user toggled WiFi. Another example is if you had specified android.app.job.JobInfo.Builder#setRequiresDeviceIdle(boolean), and the phone left its idle state. There are many other reasons a job can be stopped early besides constraints no longer being satisfied. JobParameters#getStopReason() will return the reason this method was called. You are solely responsible for the behavior of your application upon receipt of this message; your app will likely start to misbehave if you ignore it.

Once this method returns (or times out), the system releases the wakelock that it is holding on behalf of the job.

Any user-initiated job cannot be rescheduled when stopped by the user via a system provided affordance (such as the Task Manager). In such situations, the returned value from this method call is always treated as false.

Note: When a job is stopped and rescheduled via this method call, the deadline constraint is excluded from the rescheduled job's constraint set. The rescheduled job will run again once all remaining constraints are satisfied.

Parameters
params JobParameters!: The parameters identifying this job, similar to what was supplied to the job in the onStartJob(android.app.job.JobParameters) callback, but with the stop reason included.
Return
Boolean true to indicate to the JobScheduler whether you'd like to reschedule this job based on the retry criteria provided at job creation-time; or false to end the job entirely (or, for a periodic job, to reschedule it according to its requested periodic criteria). Regardless of the value returned, your job must stop executing.

setNotification

Added in API level 34
fun setNotification(
    params: JobParameters,
    notificationId: Int,
    notification: Notification,
    jobEndNotificationPolicy: Int
): Unit

Provide JobScheduler with a notification to post and tie to this job's lifecycle. This is only required for those user-initiated jobs which return true via JobParameters#isUserInitiatedJob(). If the app does not call this method for a required notification within 10 seconds after onStartJob(android.app.job.JobParameters) is called, the system will trigger an ANR and stop this job. The notification must provide an accurate description of the work that the job is doing and, if possible, the state of the work.

Note that certain types of jobs (e.g. data transfer jobs) may require the notification to have certain characteristics and their documentation will state any such requirements.

JobScheduler will not remember this notification after the job has finished running, so apps must call this every time the job is started (if required or desired).

If separate jobs use the same notification ID with this API, the most recently provided notification will be shown to the user, and the jobEndNotificationPolicy of the last job to stop will be applied.

Parameters
params JobParameters: The parameters identifying this job, as supplied to the job in the onStartJob(android.app.job.JobParameters) callback. This value cannot be null.
notificationId Int: The ID for this notification, as per android.app.NotificationManager#notify(int, * Notification).
notification Notification: The notification to be displayed. This value cannot be null.
jobEndNotificationPolicy Int: The policy to apply to the notification when the job stops. Value is android.app.job.JobService#JOB_END_NOTIFICATION_POLICY_DETACH, or android.app.job.JobService#JOB_END_NOTIFICATION_POLICY_REMOVE

updateEstimatedNetworkBytes

Added in API level 34
fun updateEstimatedNetworkBytes(
    params: JobParameters,
    downloadBytes: Long,
    uploadBytes: Long
): Unit

Update the amount of data this job is estimated to transfer after the job has started.

Parameters
params JobParameters: This value cannot be null.
downloadBytes Long: Value is a non-negative number of bytes.
uploadBytes Long: Value is a non-negative number of bytes.

updateEstimatedNetworkBytes

Added in API level 34
fun updateEstimatedNetworkBytes(
    params: JobParameters,
    jobWorkItem: JobWorkItem,
    downloadBytes: Long,
    uploadBytes: Long
): Unit

Update the amount of data this JobWorkItem is estimated to transfer after the job has started.

Parameters
params JobParameters: This value cannot be null.
jobWorkItem JobWorkItem: This value cannot be null.
downloadBytes Long: Value is a non-negative number of bytes.
uploadBytes Long: Value is a non-negative number of bytes.

updateTransferredNetworkBytes

Added in API level 34
fun updateTransferredNetworkBytes(
    params: JobParameters,
    transferredDownloadBytes: Long,
    transferredUploadBytes: Long
): Unit

Tell JobScheduler how much data has successfully been transferred for the data transfer job.

Parameters
params JobParameters: This value cannot be null.
transferredDownloadBytes Long: Value is a non-negative number of bytes.
transferredUploadBytes Long: Value is a non-negative number of bytes.

updateTransferredNetworkBytes

Added in API level 34
fun updateTransferredNetworkBytes(
    params: JobParameters,
    item: JobWorkItem,
    transferredDownloadBytes: Long,
    transferredUploadBytes: Long
): Unit

Tell JobScheduler how much data has been transferred for the data transfer JobWorkItem.

Parameters
params JobParameters: This value cannot be null.
item JobWorkItem: This value cannot be null.
transferredDownloadBytes Long: Value is a non-negative number of bytes.
transferredUploadBytes Long: Value is a non-negative number of bytes.