SlideShare a Scribd company logo
1 of 9
Easy Job Scheduling with
Android-Job
In the modern app development era, running some background
tasks outside the scope of an application’s life-cycle have
become one of the key requirements. These tasks may be as
simple as just reminding the user of something or as complex as
syncing local data with server and fetching latest data
periodically to provide better user experience. Implementing
these features in Android is really challenging and you have to
be very careful with your app performance along with other
aspects such as battery life.
Android provides several APIs for scheduling background work
(beyond the app life-cycle).
1. JobScheduler
JobScheduler was introduced in Lollipop and its the most
efficient way to perform background work, especially
networking. It performs background work based on conditions,
not on time. These conditions may be whether the device is
connected to a network, charging or idle.
JobScheduler comes with a very fluent API and its very easy to
implement. You can use JobScheduler by registering jobs
specifying their requirements for network and timing. Then the
system schedules the jobs to run at appropriate times. It also
defers the execution as necessary to comply with Doze
mode and App Standby restrictions. Also the jobs are batched
together by the system to save battery life. Another handy
feature is that the scheduled jobs are persisted through system
reboots.
JobScheduler is the way to go with API if your app targets
Lollipop (API level 21) and above.
Source: developer.android.com
2. GCM Network Manager
GCM Network Manager comes with a similar API like
JobScheduler and it targets API level 9 and above. It uses
JobScheduler behind the scene for API level 21 and higher. It
has all the battery saving scheduling features from
JobScheduler.
The main disadvantage with GCM Network Manager is it’s a
part of Google’s Play Services SDK and can be used only on
devices with Google Play preinstalled. Another got you is that all
scheduled Services will be wiped out when the application or
Google Play Service updates.
3. Alarm Manager
Though JobScheduler and GCM Network Manager are good at
performing tasks based on conditions such as network
connectivity, device charging etc. while keeping battery life in
mind, they are not meant for performing tasks immediately or
at a specific time. An Alarm Clock or Reminder App which
needs precision in timing should not use any of these options.
Instead use AlarmManager when your app needs to post a
notification or set off an alarm at a very specific time.
The AlarmManager is typically used to fire off a Pending Intent
that will start a Service in the future. It has the ability to wake
up the device if the alarm is urgent. We can use AlarmManager
for periodic tasks based on an elapsed time interval. The main
got you with AlarmManager is that the API behaviour differs
between platform versions. There’s a lot of boilerplate required
to implement AlarmManager. Also the device state is ignored.
Never use AlarmManager to perform networking tasks.
As you can see, scheduling background work in Android is quite
a headache with 3 different APIs all performing the same thing.
To overcome this problem, the nice folks at Evernote have open
sourced a unified library to schedule jobs in Android.
Meet Android-Job
Android-Job abstracts away which implementation you want
to use to perform background work.
Depending on the requirements, this library decides which
API to use to run your job.
It provides a superset of allthe features from JobScheduler,
GCM Network Manager and AlarmManager.
All features from Android Nougatare backward compatible.
Less boilerplate.
Setting up Android-Job
Include android-job dependency in your app
module’s build.gradle file and sync project.
Using Android-Job
Implementing Android-Job is super easy.
The API includes below classes/interfaces.
1. Job: Your jobs need to extend this class and
override onRunJob method. The heavy lifting is done here.
You must return a Result from this method so that the
system knows whether to attempt to run your job at a later
time.
2. Job Request: You can schedule a Job by creating
a JobRequest using its builder constructor and passing your
Job tag.
3. Job Creator: Job Creator acts like a factory to provide a
Job based on a job tag. Your concrete Job Creator class must
implement the Job Creator interface and override
the create method.
4. Job Manager: The Job Manager class serves as the entry
point. Before using this class you must initialize this as
singleton. Job Manager takes a Context. After creating the
instance, you have to add your Job Creator to Job Manager.
Here we will develop a simple app to show notification to the
user periodically.
Let’s create our ShowNotificationJob class in the first step.
In the onRunJob method we are simply showing a notification
and we are returning Result. SUCCESS every time the job runs.
Also we have a static schedule Periodic method which builds the
Job Request through its Builder and schedules the job by
calling schedule (). We are passing ShowNotificationJob.
TAG in the Builder constructor which tells our Job Creator
return a ShowNotificationJob instance.
JobRequest.Builder has many methods. Here we are calling set
Periodic to tell the system that this is a periodic job which runs
every 15 minutes. Also we have passed 5 minutes as the 2nd
parameter which is actually the flex time. This helps the system
to batch our job with any other jobs with similar time interval.
setUpdateCurrent(true) will update the current job instead of
creating a new job.
set Persisted(true) tells the system to persist the job through
system reboots.
Next let’s create our DemoJobCreator class which
implements JobCreatorinterface.
As you can see, in the create method we have a switch construct
which maps a tag with a specific job.
In the next step we will create our MainApp class which
extends Application class. In the MainApp class we will create
the Job Manager instance by passing our application context
and add our DemoJobCreator to the Job Manager.
In the final step we will call the schedule Periodic method of our
ShowNotificationJob class in the on Create method of Main
Activity to schedule our job when our application starts.
That’s it.
You can implement your Job using this library very easily. You
can create a much advanced job by creating Job Request as per
your requirements. You can see all the methods available for
creating an advanced job in their GitHub repo.
While debugging, you may set the interval time to 1 minute or
less to test the app quickly. But in Android N the minimum
interval of periodic jobs is 15 minutes. So you will get this error
while running the job.
Interval Ms is out of range
To overcome this error you can configure the JobManager
with setAllowSmallerIntervalsForMarshmallow(true) method
for debugging purpose. But remember, in production you must
set the minimum interval time to 15 times otherwise your app
may behave differently in different platform versions.
Android Training in Chennai @ Greens
Technology Learn Android Training in
Chennai At Greens Technologys—No.1 Android Training
Institute in Chennai
Rated as No.1 Leading Software Testing Training in
Chennai offering classroom training, practical training, and
online training.
Android Training Centre in Chennai is located in Adyar,
Velachery, Tambaram, and OMR. Call Now: 8939925577

More Related Content

What's hot

Mulesoft Munit Testing
Mulesoft Munit TestingMulesoft Munit Testing
Mulesoft Munit Testingakshay yeluru
 
Essentials of developing_tizen_web_application_en_1.0
Essentials of developing_tizen_web_application_en_1.0Essentials of developing_tizen_web_application_en_1.0
Essentials of developing_tizen_web_application_en_1.0Saima Ashiq
 
ML model integration with DevOps
ML model integration with DevOpsML model integration with DevOps
ML model integration with DevOpsGUNISUDHARANI
 
Progressive Mobile Test Automation
Progressive Mobile Test AutomationProgressive Mobile Test Automation
Progressive Mobile Test AutomationRakhi Jain Rohatgi
 
[@NaukriEngineering] Mobile Web app scripts execution using Appium
[@NaukriEngineering] Mobile Web app scripts execution using Appium[@NaukriEngineering] Mobile Web app scripts execution using Appium
[@NaukriEngineering] Mobile Web app scripts execution using AppiumNaukri.com
 
TestComplete – A Sophisticated Automated Testing Tool by SmartBear
TestComplete – A Sophisticated Automated Testing Tool by SmartBearTestComplete – A Sophisticated Automated Testing Tool by SmartBear
TestComplete – A Sophisticated Automated Testing Tool by SmartBearSoftware Testing Solution
 
Android new api error
Android new api errorAndroid new api error
Android new api errorcode2care
 

What's hot (7)

Mulesoft Munit Testing
Mulesoft Munit TestingMulesoft Munit Testing
Mulesoft Munit Testing
 
Essentials of developing_tizen_web_application_en_1.0
Essentials of developing_tizen_web_application_en_1.0Essentials of developing_tizen_web_application_en_1.0
Essentials of developing_tizen_web_application_en_1.0
 
ML model integration with DevOps
ML model integration with DevOpsML model integration with DevOps
ML model integration with DevOps
 
Progressive Mobile Test Automation
Progressive Mobile Test AutomationProgressive Mobile Test Automation
Progressive Mobile Test Automation
 
[@NaukriEngineering] Mobile Web app scripts execution using Appium
[@NaukriEngineering] Mobile Web app scripts execution using Appium[@NaukriEngineering] Mobile Web app scripts execution using Appium
[@NaukriEngineering] Mobile Web app scripts execution using Appium
 
TestComplete – A Sophisticated Automated Testing Tool by SmartBear
TestComplete – A Sophisticated Automated Testing Tool by SmartBearTestComplete – A Sophisticated Automated Testing Tool by SmartBear
TestComplete – A Sophisticated Automated Testing Tool by SmartBear
 
Android new api error
Android new api errorAndroid new api error
Android new api error
 

Similar to Easy job scheduling with android

Android scheduling.pptx
Android scheduling.pptxAndroid scheduling.pptx
Android scheduling.pptxZakiKhan66
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changesInnovationM
 
Job schedulers android
Job schedulers androidJob schedulers android
Job schedulers androidDeesha Vora
 
The ultimate guide to optimize your react native app performance in 2022
The ultimate guide to optimize your react native app performance in 2022The ultimate guide to optimize your react native app performance in 2022
The ultimate guide to optimize your react native app performance in 2022Katy Slemon
 
How to increase the ui performance of apps designed using react
How to increase the ui performance of apps designed using react How to increase the ui performance of apps designed using react
How to increase the ui performance of apps designed using react MoonTechnolabsPvtLtd
 
Dive into Angular, part 5: Experience
Dive into Angular, part 5: ExperienceDive into Angular, part 5: Experience
Dive into Angular, part 5: ExperienceOleksii Prohonnyi
 
GDG Devfest 2016 session on Android N
GDG Devfest 2016 session on Android NGDG Devfest 2016 session on Android N
GDG Devfest 2016 session on Android NImam Raza
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppKaty Slemon
 
4 Phases followed by the Android Application Development Company.pdf
4 Phases followed by the Android Application Development Company.pdf4 Phases followed by the Android Application Development Company.pdf
4 Phases followed by the Android Application Development Company.pdfJohn William
 
Mule soft debugprogram
Mule soft debugprogramMule soft debugprogram
Mule soft debugprogramabhipokharna
 
How to feature flag and run experiments in iOS and Android
How to feature flag and run experiments in iOS and AndroidHow to feature flag and run experiments in iOS and Android
How to feature flag and run experiments in iOS and AndroidOptimizely
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work managerlpu
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfJohnLeo57
 
Required computer skills program devlopment
Required computer skills program devlopmentRequired computer skills program devlopment
Required computer skills program devlopmentHubert Shanthan
 
ANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 schANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 schkannikadg
 
React Native: Is It Worth It? UA Mobile 2017.
React Native: Is It Worth It? UA Mobile 2017.React Native: Is It Worth It? UA Mobile 2017.
React Native: Is It Worth It? UA Mobile 2017.UA Mobile
 
Final NEWS.pdf
Final NEWS.pdfFinal NEWS.pdf
Final NEWS.pdfRebaMaheen
 
Final NewsApp.pdf
Final NewsApp.pdfFinal NewsApp.pdf
Final NewsApp.pdfRebaMaheen
 

Similar to Easy job scheduling with android (20)

Gaad01 job scheduler
Gaad01 job schedulerGaad01 job scheduler
Gaad01 job scheduler
 
Android scheduling.pptx
Android scheduling.pptxAndroid scheduling.pptx
Android scheduling.pptx
 
Android 8 behavior changes
Android 8 behavior changesAndroid 8 behavior changes
Android 8 behavior changes
 
Job schedulers android
Job schedulers androidJob schedulers android
Job schedulers android
 
The ultimate guide to optimize your react native app performance in 2022
The ultimate guide to optimize your react native app performance in 2022The ultimate guide to optimize your react native app performance in 2022
The ultimate guide to optimize your react native app performance in 2022
 
How to increase the ui performance of apps designed using react
How to increase the ui performance of apps designed using react How to increase the ui performance of apps designed using react
How to increase the ui performance of apps designed using react
 
Dive into Angular, part 5: Experience
Dive into Angular, part 5: ExperienceDive into Angular, part 5: Experience
Dive into Angular, part 5: Experience
 
GDG Devfest 2016 session on Android N
GDG Devfest 2016 session on Android NGDG Devfest 2016 session on Android N
GDG Devfest 2016 session on Android N
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
4 Phases followed by the Android Application Development Company.pdf
4 Phases followed by the Android Application Development Company.pdf4 Phases followed by the Android Application Development Company.pdf
4 Phases followed by the Android Application Development Company.pdf
 
Mule soft debugprogram
Mule soft debugprogramMule soft debugprogram
Mule soft debugprogram
 
How to feature flag and run experiments in iOS and Android
How to feature flag and run experiments in iOS and AndroidHow to feature flag and run experiments in iOS and Android
How to feature flag and run experiments in iOS and Android
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work manager
 
Codename one
Codename oneCodename one
Codename one
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
 
Required computer skills program devlopment
Required computer skills program devlopmentRequired computer skills program devlopment
Required computer skills program devlopment
 
ANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 schANGULAR JS LAB MANUAL(final) vtu2021 sch
ANGULAR JS LAB MANUAL(final) vtu2021 sch
 
React Native: Is It Worth It? UA Mobile 2017.
React Native: Is It Worth It? UA Mobile 2017.React Native: Is It Worth It? UA Mobile 2017.
React Native: Is It Worth It? UA Mobile 2017.
 
Final NEWS.pdf
Final NEWS.pdfFinal NEWS.pdf
Final NEWS.pdf
 
Final NewsApp.pdf
Final NewsApp.pdfFinal NewsApp.pdf
Final NewsApp.pdf
 

Recently uploaded

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 

Easy job scheduling with android

  • 1. Easy Job Scheduling with Android-Job In the modern app development era, running some background tasks outside the scope of an application’s life-cycle have become one of the key requirements. These tasks may be as simple as just reminding the user of something or as complex as syncing local data with server and fetching latest data periodically to provide better user experience. Implementing these features in Android is really challenging and you have to be very careful with your app performance along with other aspects such as battery life. Android provides several APIs for scheduling background work (beyond the app life-cycle). 1. JobScheduler JobScheduler was introduced in Lollipop and its the most efficient way to perform background work, especially networking. It performs background work based on conditions, not on time. These conditions may be whether the device is connected to a network, charging or idle.
  • 2. JobScheduler comes with a very fluent API and its very easy to implement. You can use JobScheduler by registering jobs specifying their requirements for network and timing. Then the system schedules the jobs to run at appropriate times. It also defers the execution as necessary to comply with Doze mode and App Standby restrictions. Also the jobs are batched together by the system to save battery life. Another handy feature is that the scheduled jobs are persisted through system reboots. JobScheduler is the way to go with API if your app targets Lollipop (API level 21) and above. Source: developer.android.com 2. GCM Network Manager GCM Network Manager comes with a similar API like JobScheduler and it targets API level 9 and above. It uses JobScheduler behind the scene for API level 21 and higher. It
  • 3. has all the battery saving scheduling features from JobScheduler. The main disadvantage with GCM Network Manager is it’s a part of Google’s Play Services SDK and can be used only on devices with Google Play preinstalled. Another got you is that all scheduled Services will be wiped out when the application or Google Play Service updates. 3. Alarm Manager Though JobScheduler and GCM Network Manager are good at performing tasks based on conditions such as network connectivity, device charging etc. while keeping battery life in mind, they are not meant for performing tasks immediately or at a specific time. An Alarm Clock or Reminder App which needs precision in timing should not use any of these options. Instead use AlarmManager when your app needs to post a notification or set off an alarm at a very specific time. The AlarmManager is typically used to fire off a Pending Intent that will start a Service in the future. It has the ability to wake up the device if the alarm is urgent. We can use AlarmManager for periodic tasks based on an elapsed time interval. The main got you with AlarmManager is that the API behaviour differs between platform versions. There’s a lot of boilerplate required to implement AlarmManager. Also the device state is ignored. Never use AlarmManager to perform networking tasks. As you can see, scheduling background work in Android is quite a headache with 3 different APIs all performing the same thing. To overcome this problem, the nice folks at Evernote have open
  • 4. sourced a unified library to schedule jobs in Android. Meet Android-Job Android-Job abstracts away which implementation you want to use to perform background work. Depending on the requirements, this library decides which API to use to run your job. It provides a superset of allthe features from JobScheduler, GCM Network Manager and AlarmManager. All features from Android Nougatare backward compatible. Less boilerplate.
  • 5. Setting up Android-Job Include android-job dependency in your app module’s build.gradle file and sync project. Using Android-Job Implementing Android-Job is super easy. The API includes below classes/interfaces. 1. Job: Your jobs need to extend this class and override onRunJob method. The heavy lifting is done here. You must return a Result from this method so that the system knows whether to attempt to run your job at a later time. 2. Job Request: You can schedule a Job by creating a JobRequest using its builder constructor and passing your Job tag. 3. Job Creator: Job Creator acts like a factory to provide a Job based on a job tag. Your concrete Job Creator class must implement the Job Creator interface and override the create method.
  • 6. 4. Job Manager: The Job Manager class serves as the entry point. Before using this class you must initialize this as singleton. Job Manager takes a Context. After creating the instance, you have to add your Job Creator to Job Manager. Here we will develop a simple app to show notification to the user periodically. Let’s create our ShowNotificationJob class in the first step. In the onRunJob method we are simply showing a notification and we are returning Result. SUCCESS every time the job runs. Also we have a static schedule Periodic method which builds the Job Request through its Builder and schedules the job by calling schedule (). We are passing ShowNotificationJob. TAG in the Builder constructor which tells our Job Creator return a ShowNotificationJob instance. JobRequest.Builder has many methods. Here we are calling set Periodic to tell the system that this is a periodic job which runs every 15 minutes. Also we have passed 5 minutes as the 2nd
  • 7. parameter which is actually the flex time. This helps the system to batch our job with any other jobs with similar time interval. setUpdateCurrent(true) will update the current job instead of creating a new job. set Persisted(true) tells the system to persist the job through system reboots. Next let’s create our DemoJobCreator class which implements JobCreatorinterface. As you can see, in the create method we have a switch construct which maps a tag with a specific job. In the next step we will create our MainApp class which extends Application class. In the MainApp class we will create the Job Manager instance by passing our application context and add our DemoJobCreator to the Job Manager.
  • 8. In the final step we will call the schedule Periodic method of our ShowNotificationJob class in the on Create method of Main Activity to schedule our job when our application starts. That’s it. You can implement your Job using this library very easily. You can create a much advanced job by creating Job Request as per your requirements. You can see all the methods available for creating an advanced job in their GitHub repo. While debugging, you may set the interval time to 1 minute or less to test the app quickly. But in Android N the minimum interval of periodic jobs is 15 minutes. So you will get this error while running the job. Interval Ms is out of range To overcome this error you can configure the JobManager with setAllowSmallerIntervalsForMarshmallow(true) method for debugging purpose. But remember, in production you must
  • 9. set the minimum interval time to 15 times otherwise your app may behave differently in different platform versions. Android Training in Chennai @ Greens Technology Learn Android Training in Chennai At Greens Technologys—No.1 Android Training Institute in Chennai Rated as No.1 Leading Software Testing Training in Chennai offering classroom training, practical training, and online training. Android Training Centre in Chennai is located in Adyar, Velachery, Tambaram, and OMR. Call Now: 8939925577