Android-Job

Android library to handle jobs in the background.

Overview

Android provides three different APIs to run tasks in the future. All of them have their benefits and downsides. The AlarmManager’s API has changed over time, so you need to be careful which method you use on which platform. The JobScheduler is only available on Android Lollipop and Marshmallow, whereas the GcmNetworkManager is only available on devices with Google Play preinstalled.

There are three options with changing API levels, so it can be hard to know which one you need. You will also end up with many different paths in your code all doing the same for a different environment. We're open-sourcing this unified library to schedule jobs on Android. Depending on your requirements, this library decides which API suits your job. It provides a superset of all features from the existing AlarmManager, JobScheduler and GcmNetworkManager, e.g. you can run your job only if the device has a working Internet connection and is charging.

Setting up the library is straightforward. You only need to initialize the JobManager and then you can start scheduling your jobs. You don’t need to declare any services, receivers or permissions in your manifest.

Download

Download the latest version or grab via Gradle:

dependencies {
    compile 'com.evernote:android-job:1.4.2'
}

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 recommend to initialize the JobManager in the onCreate() method of your Application object.

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        JobManager.create(this).addJobCreator(new DemoJobCreator());
    }
}
public class DemoJobCreator implements JobCreator {

    @Override
    public Job create(String tag) {
        switch (tag) {
            case DemoJob.TAG:
                return new DemoJob();
            default:
                return null;
        }
    }
}

After that you can start scheduling jobs.

public class DemoJob extends Job {

    public static final String TAG = "job_demo_tag";

    @Override
    @NonNull
    protected Result onRunJob(Params params) {
        // run your job
        return Result.SUCCESS;
    }
}

private void scheduleJob() {
    new JobRequest.Builder(DemoJob.TAG)
            .setExecutionWindow(30_000L, 40_000L)
            .build()
            .schedule();
}