Android-Job


Source link: https://github.com/evernote/android-job

Android-Job

A utility library for Android to run jobs delayed in the background. Depending on the Android version either the JobScheduler, GcmNetworkManager or AlarmManager is getting used. You can find out in this blog post or in these slides why you should prefer this library than each separate API. All features from Android Oreo are backward compatible back to Ice Cream Sandwich.

Download

Download the latest version or grab via Gradle:

dependencies {

  compile 'com.evernote:android-job:1.2.0' 
}

If you didn't turn off the manifest merger from the Gradle build tools, then no further step is required to setup the library. Otherwise you manually need to add the permissions and services like in this AndroidManifest.

You can read the JavaDoc here.

Usage

The class JobManager serves as entry point. Your jobs need to extend the class Job. Create a JobRequest with the corresponding builder class and schedule this request with the JobManager.

Before you can use the JobManager you must initialize the singleton. You need to provide a Context and add a JobCreator implementation after that. The JobCreator maps a job tag to a specific job class. It's recommended to initialize the JobManager in the onCreate() method of your Application object, but there is an alternative, if you don't have access to the Application class.

public class App extends Application {

@Override
  public void onCreate() {

super.onCreate();

JobManager.create(this).addJobCreator(new DemoJobCreator());

  
}
 
}
public class DemoJobCreator implements JobCreator {

@Override
  @Nullable
  public Job create(@NonNull String tag) {

switch (tag) {

 case DemoSyncJob.TAG:

  return new DemoSyncJob();

 default:

  return null;

}

  
}
 
}

After that you can start scheduling jobs.

public class DemoSyncJob extends Job {

public static final String TAG = "job_demo_tag";

@Override
  @NonNull
  protected Result onRunJob(Params params) {

// run your job here

return Result.SUCCESS;
  
}

public static void scheduleJob() {

new JobRequest.Builder(DemoSyncJob.TAG)

  .setExecutionWindow(30_000L, 40_000L)

  .build()

  .schedule();

  
}
 
}

Advanced

The JobRequest.Builder class has many extra options, e.g. you can specify a required network connection, make the job periodic, pass some extras with a bundle, restore the job after a reboot or run the job at an exact time.

Each job has a unique ID. This ID helps to identify the job later to update requirements or to cancel the job.

private void scheduleAdvancedJob() {

  PersistableBundleCompat extras = new PersistableBundleCompat();

  extras.putString("key", "Hello world");

int jobId = new JobRequest.Builder(DemoSyncJob.TAG)

 .setExecutionWindow(30_000L, 40_000L)

 .setBackoffCriteria(5_000L, JobRequest.BackoffPolicy.EXPONENTIAL)

 .setRequiresCharging(true)

 .setRequiresDeviceIdle(false)

 .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)

 .setExtras(extras)

 .setRequirementsEnforced(true)

 .setUpdateCurrent(true)

 .build()

 .schedule();
 
}
  private void schedulePeriodicJob() {

  int jobId = new JobRequest.Builder(DemoSyncJob.TAG)

 .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))

 .build()

 .schedule();
 
}
  private void scheduleExactJob() {

  int jobId = new JobRequest.Builder(DemoSyncJob.TAG)

 .setExact(20_000L)

 .build()

 .schedule();
 
}
  private void runJobImmediately() {

  int jobId = new JobRequest.Builder(DemoSyncJob.TAG)

 .startNow()

 .build()

 .schedule();
 
}
  private void cancelJob(int jobId) {

  JobManager.instance().cancel(jobId);
 
}

If a non periodic Job fails, then you can reschedule it with the defined back-off criteria.

public class RescheduleDemoJob extends Job {

@Override
  @NonNull
  protected Result onRunJob(Params params) {

// something strange happened, try again later

return Result.RESCHEDULE;
  
}

@Override
  protected void onReschedule(int newJobId) {

// the rescheduled job has a new ID
  
}
 
}

Proguard

The library doesn't use reflection, but it relies on three Services and two BroadcastReceivers. In order to avoid any issues, you shouldn't obfuscate those four classes. The library bundles its own Proguard config and you don't need to do anything, but just in case you can add these rules in your configuration.

More questions?

See the FAQ in the Wiki.

Google Play Services

This library does not automatically bundle the Google Play Services, because the dependency is really heavy and not all apps want to include them. That's why you need to add the dependency manually, if you want that the library uses the GcmNetworkManager on Android 4.

dependencies {

  compile "com.google.android.gms:play-services-gcm:latest_version" 
}

Crashes after removing the GCM dependency is a known limitation of the Google Play Services. Please take a look at this workaround to avoid those crashes.

License

Copyright (c) 2007-2017 by Evernote Corporation, All rights reserved.  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

An Android library that checks for your application's updates on Google Play Store. This library uses Android Publisher API.

This plugin integrates Google Play Developer API (Publishing API) with the Gradle build system. With this plugin, you can upload apks and listings directly via command line, IntelliJ, Android Studio and other IDEs.

RxJava extension for Android to access camera and gallery to take images.

This library allows you to create a shadow effect for your layout based on your child.

Simple chart for Android.

Animations for support.v4.Fragment transitions.

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