Upgrade to Pro — share decks privately, control downloads, hide ads and more …

A Simple Android Background Task Scheduler

A Simple Android Background Task Scheduler

Android-Priority-Jobqueue (APJQ)
(This tech talk was presented on BlrDroid September 2014 Meetup)

Update: new version of APJQ released in August 2016 with more features, I'm working on it, stay tuned for updated version with detailed sample.

A Job Queue developed by Path (Path.com) initially and then it’s maintained by Yigit Boyar a Googler!, It’s specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability.

Job Queue was inspired by a Google I/O 2010 talk on REST client applications

Almost every application does work in a background thread. These "background tasks" are expected to keep the application responsive and robust, especially during unfavorable situations (e.g. limited network connectivity).

Jobqueue gives simple solution to achieve Background Jobs compare to other implementations in Android.

Note:
Now https://github.com/path/android-priority-jobqueue
moved to
https://github.com/yigit/android-priority-jobqueue/

Subrahmanya S M

September 27, 2014
Tweet

Other Decks in Programming

Transcript

  1. A Simple Android Background Task Scheduler. What I have tried/learned

    with one more way to do the background task! Subrahmanya S M
  2. About Me: • Got to know about "Anyone can learn

    anything and become good at it!" from my Gurus. • Learnt Java programing at Uttara Infosolutions. • Got inspiration about Android App Dev from Blrdroid 11th Meetup. • Currently Working as an Android application Developer.
  3. Agenda: • Ways to implement background work/task in Android. •

    What I have tried/learned new with Android-Priority-Jobqueue. • Show me the code. • A very simple Application Demo. • Advantages Disadvantages. • Question and Answer
  4. Background work in Android: Ways to implement background work: ➔

    Async Task ➔ Loaders ➔ Service. ➔ Others: RoboSpice, RxJava etc
  5. Async Task Cons: • Different behavior in different versions of

    android. • AsyncTasks don't follow Activity life cycle. • It is a terrible idea to drop a response from a network request just because a user rotated his/her phone. • References the Activity or parts of the View hierarchy, we can easily leak a significant amount of memory in this way. • Using it as anonymous inner class of the host Activity, which creates an implicit reference to the Activity and an even bigger memory leak. Internals Ref: http://www.slideshare.net/blrdroid/internals-of-asynctask by Amrith Sanjeev Isuues Ref: https://www.packtpub.com/books/content/common-asynctask-issues
  6. TestAsyncTask myATask = new TestAsyncTask(); for (int i = 0;

    i < count; i++) { myATask.execute("one", "two", "three", "four"); } But you can do : for (int i = 0; i < count; i++) { TestAsyncTask myATask = new TestAsyncTask(); myATask.execute("one", "two", "three", "four"); }
  7. Service IntentService AsyncTask When to use ? Task with no

    UI, but shouldn't be too long. Use threads within service for long tasks. - Long task. - If communication is required, can use main thread handler or broadcast intents - When callbacks are needed (Intent triggered tasks). - Small task having to communicate with main thread. - For tasks in parallel use multiple instances OR Executor Trigger Call to method onStartService() Intent Call to method execute() Triggered Thread Any thread Main Thread (Intent is received on main thread and then worker thread is spawed) Main Thread Runs On (thread) Main Thread Separate worker thread Worker thread. However, Main thread methods may be invoked in between to publish progress. Limitations / Drawbacks May block the main thread Cannot run tasks in parallel. - Multiple intents are queued on the same worker thread. -ThreadPoolExecutor needed . No task prioritization No persist requests to disk . - one instance can only be executed once (hence cannot run in a loop) - Must be created and executed from the Main thread -Different behavior in different versions of android.
  8. Service: Cons: • Service May block main(UI) thread. • You

    will need a thread pool (e.g. ThreadPoolExecutor) to process requests in parallel, broadcast events to update the UI. • The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially • We need to write additional code to persist queued requests to disk. • As your application grows, the number of background operations grows, which force you to consider task prioritization and often-complicated concurrency problems.
  9. Android-Priority-Jobqueue (APJQ) What is Android-Priority-Jobqueue? A Job Queue developed by

    Path (Path.com) initially and then it’s maintained by Yigit Boyar a Googler!, It’s specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability. Job Queue was inspired by a Google I/O 2010 talk on REST client applications Almost every application does work in a background thread. These "background tasks" are expected to keep the application responsive and robust, especially during unfavorable situations (e.g. limited network connectivity). Jobqueue gives simple solution to achieve Background Jobs compare to other implementations in Android. Note: Now https://github.com/path/android-priority-jobqueue moved to https://github.com/yigit/android-priority-jobqueue/
  10. Show me the code: //... public void onSendClick() { final

    String status = editText.getText().toString(); if(status.trim().length() > 0) { jobManager.addJobInBackground(new PostTweetJob(status)); editText.setText(""); } } ...
  11. public class PostTweetJob extends Job { private String text; public

    PostTweetJob(String text) { // Job Config: This job requires network connectivity,should be persisted in case the application exits. super(new Params(PRIORITY.High).requireNetwork().persist()); } @Override public void onAdded() { // Job has been saved to disk. good place to dispatch a UI event } @Override public void onRun() throws Throwable { // Job logic goes here. In this example, the network call REST api. } @Override protected boolean shouldReRunOnThrowable(Throwable throwable) { // An error occurred in onRun.Return value determines whether this job should retry running (true) or abort (false). } @Override protected void onCancel() { // Job has exceeded retry attempts or shouldReRunOnThrowable() has returned false. } }
  12. Job Manager Configuration: Configuration configuration = new Configuration.Builder (this) .customLogger(new

    CustomLogger() { private static final String TAG = "JOBS"; @Override public boolean isDebugEnabled() { return true; } . . ) .minConsumerCount(1)//always keep at least one consumer alive .maxConsumerCount(3)//up to 3 consumers at a time .loadFactor(3)//3 jobs per consumer .consumerKeepAlive(120)//wait 2 minute .build(); jobManager = new JobManager(this, configuration);
  13. Job Manager Features For Jobs • Consumer Threads • Job

    Queues • Job Persistence • Network Utility • Dependency Injection • Multiple Job Managers • Logs
  14. Job Configuration: • Network Requirement : new Params(Priority.HIGH).requireNetwork().persist() • Grouping:

    new Params(0).groupBy("group1") • Persistence new Params(0).persist().groupBy("group2") new Params(0).persist().groupBy("group1") • Delaying Jobs new Params(Priority.LOW).requireNetwork().delayInMs(TimeUtil.MS_PER_SECOND * 30)); Job: Job A, requires network, group X Job B, does not require network, group X Job Manager Solution: if there is no network connection, JobManager will still run Job B but will wait for network connection to run Job A .
  15. When app starts but you don't want it to fight

    for network with your more important requests.
  16. Advantages: • It is very easy to de-couple application logic

    from your activites. • You don't have to deal with AsyncTask lifecycles. This is true assuming you use an event bus to update your UI • Job Queue takes care of prioritizing jobs, checking network connection, running them in parallel, etc • You can delay jobs.you don't want it to interfere with critical network operations (e.g. fetching user-facing content • You can group jobs to ensure their serial execution, if necessary Ex: Chat Clients. • By default, Job Queue monitors network connectivity (so you don't need to worry about it). When a device is operating offline, jobs that require the network won't run until connectivity is restored. You can even provide a custom NetworkUtil if you need custom logic.
  17. Disadvantages: • Job Manager Config features needs a L Developer

    Preview new android.app.job.JobScheduler API kind of Network Util for optimize battery life . • Java serialization in android is inefficient the “parcelable” operation is much more faster. • Job Manager Configuration does not have Dynamic configurations Properties when network switches from LTE/WiFi/3G/2G. We need implement provide a custom NetworkUtil. • Job Manager doesn't have support like startForeground() like Android Service. • There are some custom implementation when Device rebooted to wake up the JobManager !! • kryo like Java serialization and cloning mobile friendly fast, efficient, automatic are not used!.
  18. References: https://github.com/path/android-priority-jobqueue (depricated old repo) https://github.com/yigit/android-priority-jobqueue (New) https://github.com/LOG-TAG/android-priority-jobqueue-examples (Job queue,

    retry examples) Update: New update from Yigit’s talk ‘Sample Application for The Android Architecture Talk’ @ Android Dev Summit 2015 https://github.com/yigit/dev-summit-architecture-demo
  19. QA? (if don’t have any questions, browse through the issues

    you will get more info, doubts : ) ) https://github.com/yigit/android-priority-jobqueue/issues
  20. Credits Thanks to • Blrdroid Organizers • 3891+ Blrdroid members

    • Contributor of android-priority-jobqueue Yigit BoyarGoogle Subrahmanya SM @LOG_TAG https://about.me/subrahmanyasm