当前位置: 首页 > 软件库 > 手机/移动开发 > >

android-job

Android library to handle jobs in the background.
授权协议 Apache-2.0 License
开发语言 Java
所属分类 手机/移动开发
软件类型 开源软件
地区 不详
投 递 者 鲜于峰
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

DEPRECATED

This library is not maintained anymore and there will be no further releases except for very critical bug fixes. Use WorkManager instead of this library.

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 {
    implementation 'com.evernote:android-job:1.4.2'
}

Starting with version 1.3.0 the library will use the WorkManager internally, please read the documentation and opt-in.

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.

WorkManager

WorkManager is a new architecture component from Google and tries to solve a very similar problem this library tries to solve: implementing background jobs only once for all Android versions. The API is very similar to this library, but provides more features like chaining work items and it runs its own executor.

If you start a new project, you should be using WorkManager instead of this library. You should also start migrating your code from this library to WorkManager. At some point in the future this library will be deprecated.

Starting with version 1.3.0 this library will use the WorkManager internally for scheduling jobs. That should ease the transition to the new architecture component. You only need to add the WorkManager to your classpath, e.g.

dependencies {
    implementation "android.arch.work:work-runtime:$work_version"
}

Please take a look at the Wiki for a complete transition guide.

The API and feature set of android-job and WorkManager are really similar. However, some features are unique and only supported by one or the other

Feature android-job WorkManager
Exact jobs Yes No
Transient jobs Yes No
Daily jobs Yes No
Custom Logger Yes No
Observe job status No Yes
Chained jobs No Yes
Work sequences No Yes

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, then include the following dependency.

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

Because of recent changes in the support library, you must turn on the service manually in your AndroidManifest.xml

<service
    android:name="com.evernote.android.job.gcm.PlatformGcmService"
    android:enabled="true"
    tools:replace="android:enabled"/>

If you don't turn on the service, the library will always use the AlarmManager on Android 4.x.

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.
  • package zhang.phil; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.widget.Toast; imp

  • Priority Job Queue is an implementation of a Job Queue specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability. 项目地址:https:/

  • 项目中用到了android-priority-jobqueue-2.0.1这个开源库,发包给测试的时候发现有时候APP会闪退,查了下报错信息,主要是下面这段 android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed. at android.database.Curso

  • 34.13.2 JobScheduler的替代方案     前面提到,使用JobScheduler时,即使执行任务的条件不满足,任务也会被执行;为了规避这个缺陷,可以使用Evernote提供的库让APP定期执行任务,以下是具体的实现方式。   在build.gradle文件中增加库的依赖: dependencies {     …     compile 'com.evernote:android

  • 接上篇:安卓无障碍API封装库: Android-Accessibility-Api 本次2.0更新带来了: 添加SmartFinder 支持多条件随意组合 搜索 支持条件扩展 协程支持 SmartFinder 介绍 1. 自定义条件搜索 搜索 AccessibilityNodeInfo.isChecked 为 true 的 //SF 为 SmartFinder缩写 SF.where { node

 相关资料
  • JNI绑定 Android上的Java资源 WebView代码组织

  • Native.js for Android封装一条通过JS语法直接调用Native Java接口通道,通过plus.android可调用几乎所有的系统API。 方法: currentWebview: 获取当前Webview窗口对象的native层实例对象 newObject: 创建实例对象 getAttribute: 获取对象(类对象/实例对象)的属性值 setAttribute: 设置对象(类对

  • Android++ 是一个免费的 Visual Studio 扩展,用于支持在 Visual Studio 上开发和调试原生的 Android 应用,主要基于 NDK 的 C/C++ 应用。同时包括可订制的发布、资源管理以及集成了 Java 源码编译。

  • Android(安卓)是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国谷歌公司和开放手机联盟领导及开发。Android操作系统最初由Andy Rubin开发,主要支持手机。2005年8月由谷歌收购注资。2007年11月,谷歌与84家硬件制造商、软件开发商及电信营运商组建开放手机联盟共同研发改良Android系统。随后谷歌以Apache许可证的授

  • Android(安卓)是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国谷歌公司和开放手机联盟领导及开发。Android操作系统最初由Andy Rubin开发,主要支持手机。2005年8月由谷歌收购注资。2007年11月,谷歌与84家硬件制造商、软件开发商及电信营运商组建开放手机联盟共同研发改良Android系统。随后谷歌以Apache许可证的授

  • 简介 该库提供J2SE的Swing、AWT等类的安卓实现,引用该库便能在Android上运行J2SE应用程序。 该库实现大多数必需功能,但不是全部的J2SE。 成功示例HomeCenter服务器,该服务器基于J2SE,同时完全运行于Android之上。 使用指引 该库依赖于开源工程HomeCenter。 它不含Activity,需另建Android工程,并引用本库。 Activity和res需作为

  • 前言 少年时我们追求激情,成熟后却迷恋平庸,在我们寻找,伤害,背离之后,还能一如既往的相信爱情,这是一种勇气,每个人都有属于自己的一片森林,迷失的人迷失了,相逢的人会再相逢。 没有人觉得自己差人一等,也没有人一直喜欢居于他人之下,身为一个Android程序员,只有不断的学习,不断的付出自己的努力,自己的汗水,自己的时间,才能让自己进步,学无止境。就上篇而言,我接着来讲一下Android面试时And

  • 我的应用程序上有WebView,我在android 7.0上从用户那里得到了许多相同的错误,同时膨胀了WebView片段。 错误日志: Android看法充气异常:二进制XML文件行#8:二进制XML文件行#8:错误充气类android。网络工具包。网络视图导致:android。看法充气异常:二进制XML文件行#8:充气类android时出错。网络工具包。网络视图 网络视图片段布局: 我从这些设备