Search code examples
androidjobservice

What happens if I don't call jobFinished for a JobService?


Out of interest and to better understand error scenarios: I have a JobService. In onStartJob I return true to inform the JobManager that there's additional work. The Android documentation mentions that I need to call jobFinished to let JobManager know that the job is finished.

Now I wonder (and might have a bug based on that): What will happen if I never call jobFinished? Will Android kill the job service at some point? Will it allow for new instances of the JobService to be spawned? Or will it prevent additional services to start? Is there a maximum number of JobServices that can coexist?


Solution

  • What will happen if I never call jobFinished?

    A JobService holds a wakelock for as long as it is (or thinks it is) doing work. In a scenario where you return true from onStartJob() you are responsible for notifying the system when the job is done.

    By calling jobFinished() you indicate the work is done, and the JobService then knows it can release the wakelock. If you don't call jobFinished(), the wakelock is not released and will keep draining the CPU.

    Will Android kill the job service at some point?

    JobService is a subclass of Service so yes. Under certain conditions the OS kills off services (low on memory for example).

    Will it allow for new instances of the JobService to be spawned? Or will it prevent additional services to start? Is there a maximum number of JobServices that can coexist?

    • You do not manually create/instantiate JobServices.
    • A JobService will only handle one job at a time.

    If you schedule() new jobs for the same JobService and with the same JobInfo id, the current job will be stopped and the new one will be started.

    int schedule (JobInfo job)
    

    Schedule a job to be executed. Will replace any currently scheduled job with the same ID with the new information in the JobInfo. If a job with the given ID is currently running, it will be stopped.


    If you enqueue() new jobs for the same JobService, they will be executed only after the current job is done. If you fail to call jobFinished(), the next job in the queue will not run.

    int enqueue (JobInfo job, work)
    

    Similar to schedule(JobInfo), but allows you to enqueue work for a new or existing job. If a job with the same ID is already scheduled, it will be replaced with the new JobInfo, but any previously enqueued work will remain and be dispatched the next time it runs. If a job with the same ID is already running, the new work will be enqueued for it.

    Queueing up jobs for the same JobService works a bit differently than scheduling them with schedule(). For a complete reference, see its docs.