JobScheduler – Android Studio Tutorial
Since Android Oreo, idle apps can’t keep background services running anymore. So if you need to do operations even if your app is not running in the foreground, you should use a JobScheduler instead.
In this video we will set up such a JobScheduler by creating a class that extends JobService and then scheduling it with the JOB_SCHEDULER_SERVICE.
In the JobService class, we override onStartJob and onStopJob. In onStartJob we will start a background thread to do some long running (fake) operations. In onStopJob we cancel our work because the system will release the wakelock when the criteria for our job are not met anymore (for example we required an unmetered network and the user disables WiFi). In this case we will reschedule our task to try again later.
When we schedule our job, we pass a JobInfo object to the JobScheduler, which will define under which circumstances we want the system to execute our job. Here we can set criteria like setRequiresDeviceCharging, setRequiredNetworkType, setPeriodic and more. We can even make it survive device reboots with setPersisted.
Lastly we register our JobService in the manifest with the android.permission.BIND_JOB_SERVICE permission and the system will then start our service at the appropriate time, even if our app is not running.
Example code:
https://gist.github.com/codinginflow/4c85bfb052cd7a92ef816ab1845c669a
JobInfo.Builder documentation:
https://developer.android.com/reference/android/app/job/JobInfo.Builder.html
____________________
💻 Find the BEST programming tutorials on TutHub:
https://tuthub.io
⭐ Get my MVVM Caching Course now:
https://codinginflow.com/caching
❗ Subscribe to the channel:
https://www.youtube.com/c/codinginflo…
📨 Subscribe to the Coding in Flow newsletter:
https://codinginflow.com/newsletter
❓ Join our free developer community:
https://discord.gg/TSnMvmc
📣 Follow Coding in Flow on other sites:
Facebook: https://www.facebook.com/codinginflow
Instagram: https://www.instagram.com/codinginflow
TikTok: https://www.tiktok.com/@codinginflow
Twitter: https://twitter.com/codinginflow
Github: https://github.com/codinginflow
💰 Business requests, sponsoring, etc.: info@codinginflow.com
Views :175786
android studio