JobService


public abstract class JobService
extends Service

java.lang.Object
   ↳ android.content.Context
     ↳ android.content.ContextWrapper
       ↳ android.app.Service
         ↳ android.app.job.JobService


Entry point for the callback from the 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 Handler running on your application's main thread. This means that you must offload your execution logic to another thread/handler/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 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 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

int JOB_END_NOTIFICATION_POLICY_DETACH

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

int JOB_END_NOTIFICATION_POLICY_REMOVE

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

String PERMISSION_BIND

Job services must be protected with this permission:

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

Inherited constants

Public constructors

JobService()

Public methods

final void jobFinished(JobParameters params, boolean wantsReschedule)

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

void onNetworkChanged(JobParameters params)

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 onStartJob(JobParameters params)

Called to indicate that the job has begun executing.

abstract boolean onStopJob(JobParameters params)

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

final void setNotification(JobParameters params, int notificationId, Notification notification, int jobEndNotificationPolicy)

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

final void updateEstimatedNetworkBytes(JobParameters params, JobWorkItem jobWorkItem, long downloadBytes, long uploadBytes)

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

final void updateEstimatedNetworkBytes(JobParameters params, long downloadBytes, long uploadBytes)

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

final void updateTransferredNetworkBytes(JobParameters params, long transferredDownloadBytes, long transferredUploadBytes)

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

final void updateTransferredNetworkBytes(JobParameters params, JobWorkItem item, long transferredDownloadBytes, long transferredUploadBytes)

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

Inherited methods

Constants

JOB_END_NOTIFICATION_POLICY_DETACH

Added in API level 34
public static final int JOB_END_NOTIFICATION_POLICY_DETACH

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.

Constant Value: 0 (0x00000000)

JOB_END_NOTIFICATION_POLICY_REMOVE

Added in API level 34
public static final int JOB_END_NOTIFICATION_POLICY_REMOVE

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.

Constant Value: 1 (0x00000001)

PERMISSION_BIND

Added in API level 21
public static final String PERMISSION_BIND

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.

Constant Value: "android.permission.BIND_JOB_SERVICE"

Public constructors

JobService

public JobService ()

Public methods

jobFinished

Added in API level 21
public final void jobFinished (JobParameters params, 
                boolean wantsReschedule)

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 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
public void onNetworkChanged (JobParameters params)

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
public abstract boolean onStartJob (JobParameters params)

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

Returns
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
public abstract boolean onStopJob (JobParameters params)

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 JobInfo.Builder.setRequiredNetworkType(int), yet while your job was executing the user toggled WiFi. Another example is if you had specified 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.

Returns
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
public final void setNotification (JobParameters params, 
                int notificationId, 
                Notification notification, 
                int jobEndNotificationPolicy)

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 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 JOB_END_NOTIFICATION_POLICY_DETACH, or JOB_END_NOTIFICATION_POLICY_REMOVE

updateEstimatedNetworkBytes

Added in API level 34
public final void updateEstimatedNetworkBytes (JobParameters params, 
                JobWorkItem jobWorkItem, 
                long downloadBytes, 
                long uploadBytes)

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.

updateEstimatedNetworkBytes

Added in API level 34
public final void updateEstimatedNetworkBytes (JobParameters params, 
                long downloadBytes, 
                long uploadBytes)

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.

updateTransferredNetworkBytes

Added in API level 34
public final void updateTransferredNetworkBytes (JobParameters params, 
                long transferredDownloadBytes, 
                long transferredUploadBytes)

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
public final void updateTransferredNetworkBytes (JobParameters params, 
                JobWorkItem item, 
                long transferredDownloadBytes, 
                long transferredUploadBytes)

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.