Firebase JobDispatcher


Source link: https://github.com/firebase/firebase-jobdispatcher-android

Firebase JobDispatcher

The Firebase JobDispatcher is a library for scheduling background jobs in your Android app. It provides a JobScheduler-compatible API that works on all recent versions of Android (API level 9+) that have Google Play services installed.

Overview

What's a JobScheduler?

The JobScheduler is an Android system service available on API levels 21 (Lollipop)+. It provides an API for scheduling units of work (represented by JobService subclasses) that will be executed in your app's process.

Why is this better than background services and listening for system broadcasts?

Running apps in the background is expensive, which is especially harmful when they're not actively doing work that's important to the user. That problem is multiplied when those background services are listening for frequently sent broadcasts ( android.net.conn.CONNECTIVITY_CHANGE and android.hardware.action.NEW_PICTURE are common examples). Even worse, there's no way of specifying prerequisites for these broadcasts. Listening for CONNECTIVITY_CHANGE broadcasts does not guarantee that the device has an active network connection, only that the connection was recently changed.

In recognition of these issues, the Android framework team created the JobScheduler. This provides developers a simple way of specifying runtime constraints on their jobs. Available constraints include network type, charging state, and idle state.

This library uses the scheduling engine inside Google Play services(formerly the GCM Network Manager component) to provide a backwards compatible (back to Gingerbread) JobScheduler-like API.

This I/O presentation has more information on why background services can be harmful and what you can do about them:

There's more information on upcoming changes to Android's approach to background services on the Android developer preview page.

Requirements

The FirebaseJobDispatcher currently relies on the scheduling component in Google Play services. Because of that, it won't work on environments without Google Play services installed.

Comparison to other libraries

Library Minimum API Requires Google Play Service API 1 Custom retry strategies
Framework JobScheduler 21 No JobScheduler Yes
Firebase JobDispatcher 9 Yes JobScheduler Yes
evernote/android-job 14 No 2 Custom Yes

1: Refers to the methods that need to be implemented in the Service subclass.
2: Uses AlarmManager to support API levels <= 21 if Google Play services is unavailable.

Getting started

Installation

Add the following to your build.gradle's dependencies section:

compile 'com.firebase:firebase-jobdispatcher:0.8.4' 

Usage

Writing a new JobService

The simplest possible JobService:

import com.firebase.jobdispatcher.JobParameters; import com.firebase.jobdispatcher.JobService;  public class MyJobService extends JobService {

  @Override
  public boolean onStartJob(JobParameters job) {

// Do some work here

 return false; // Answers the question: "Is there still work going on?"
  
}

@Override
  public boolean onStopJob(JobParameters job) {

return false; // Answers the question: "Should this job be retried?"
  
}
 
}

Adding it to the manifest

<service
  android:exported="false"
  android:name=".MyJobService">
  <intent-filter>

<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
  </intent-filter> </service>

Creating a Dispatcher

// Create a new dispatcher using the Google Play driver. FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));

Scheduling a simple job

Job myJob = dispatcher.newJobBuilder()
  .setService(MyJobService.class) // the JobService that will be called
  .setTag("my-unique-tag")

  // uniquely identifies the job
  .build();
  dispatcher.mustSchedule(myJob);

Scheduling a more complex job

Bundle myExtrasBundle = new Bundle();
 myExtrasBundle.putString("some_key", "some_value");
  Job myJob = dispatcher.newJobBuilder()
  // the JobService that will be called
  .setService(MyJobService.class)
  // uniquely identifies the job
  .setTag("my-unique-tag")
  // one-off job
  .setRecurring(false)
  // don't persist past a device reboot
  .setLifetime(Lifetime.UNTIL_NEXT_BOOT)
  // start between 0 and 60 seconds from now
  .setTrigger(Trigger.executionWindow(0, 60))
  // don't overwrite an existing job with the same tag
  .setReplaceCurrent(false)
  // retry with exponential backoff
  .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
  // constraints that need to be satisfied for the job to run
  .setConstraints(

// only run on an unmetered network

Constraint.ON_UNMETERED_NETWORK,

// only run when the device is charging

Constraint.DEVICE_CHARGING
  )
  .setExtras(myExtrasBundle)
  .build();
  dispatcher.mustSchedule(myJob);

Cancelling a job

dispatcher.cancel("my-unique-tag");

Cancelling all jobs

dispatcher.cancelAll();

Contributing

See the CONTRIBUTING.md file.

Support

This library is actively supported by Google engineers. If you encounter any problems, please create an issue in our tracker.

License

Apache, see the LICENSE file.

Resources

A light but powerful ORM and SQL query generator for Java/Android with RxJava and Java 8 support.

Automated localized screenshots of your Android app on every device.

NoseyExplorer is a simple explorer that lets you see the data that Realm.io has saved for your models.

Simply register your models and your ready to start browsing your data from within your app.

Simplify getting user's location for Android.

A helper class to make any view rotatable.

Track activities, getCurrentActivity, check whether application is running or not, finish all activities, and so on.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes