Basic usage Create a new JobService This is done by extending the JobService class and implementing/overriding the required methods onStartJob() and onStopJob(). Add the new JobService to your AndroidManifest.xml The following step is mandatory, otherwise you won't be able to run your job: Declare your MyJobService class as a new <service> element between <application> </application> in your AndroidManifest.xml. Setup and run the job After you implemented a new JobService and added it to your AndroidManifest.xml, you can continue with the final steps. onButtonClick_startJob() prepares and runs a periodical job. Besides periodic jobs, JobInfo.Builder allows to specify many other settings and constraints. For example you can define that a plugged in charger or a network connection is required to run the job. onButtonClick_stopJob() cancels all running jobs After calling onButtonClick_startJob(), the job will approximately run in intervals of 10 seconds, even when the app is in the paused state (user pressed home button and app is no longer visible). Instead of cancelling all running jobs inside onButtonClick_stopJob(), you can also call jobScheduler.cancel() to cancel a specific job based on it's job ID. Beware of running lots of code or doing heavy work inside your JobService, for example in onStartJob(). The code will run on the main/UI thread and therefore can lead to a blocked UI, no longer responding app or even a crash of your app! Because of that, you must offload the work, for example by using a Thread or AsyncTask. |