JobIntentService无法在Android 8.0上立即启动

Pru*_*hvi 8 android android-intent android-intentservice android-8.0-oreo

我已经实现JobIntentService了一些后台任务,可以在较旧的Android设备上运行(Android O之前).我看到意图立即处理,但在Android O设备上JobIntentService.onHandleWork()执行之前有一些延迟.我知道意图是串行处理的,但即使队列中没有处理意图,我也会看到延迟.是因为作业调度是在Android O内部处理的吗?

在这里,Android文档说

"当作为pre-O服务运行时,排队工作的行为通常会立即启动服务,无论设备是在打瞌睡还是在其他条件下.当作为Job运行时,它将遵循标准的JobScheduler策略使用 setOverrideDeadline(long)0的作业:当设备打瞌睡时,作业将无法运行,如果设备处于强大的内存压力下并且需要大量运行作业,则可能会延迟服务.

即使我的应用程序针对API 25但在OS Android O上运行,上述语句是否有效?如果是这样,是否有任何解决方法可以立即在Android O上启动服务/作业?

我目前的实施:

public class MySampleService extends JobIntentService {

    private static final int JOB_ID = 1000;

    public MySampleService() {

    }

    /**
     * Convenience method for enqueuing work in to this service.
     */
    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, MySampleService.class, JOB_ID, work);
    }

    /**
     * Interpret the incoming intent actions and handle it appropriately.
     * @param workIntent
     */
    @Override
    protected void onHandleWork(@NonNull Intent workIntent) {
        if(workIntent==null || workIntent.getAction() == null){
            return;
        }
        /* This gets printed immediately on pre Android O devices but not otherwise*/
        System.out.println("Intent Handled");
    }
}
Run Code Online (Sandbox Code Playgroud)

Com*_*are 6

即使我的应用程序针对API 25但在OS Android O上运行,上述声明也有效吗?

是。JobIntentService行为(是否使用JobScheduler)取决于您所运行的Android版本。您targetSdkVersion没有影响。

如果是这样,是否有解决方法可立即在Android O上启动服务/作业?

不要使用JobIntentService。使用常规的前台服务。根据定义,JobScheduler可以按自己的计划安排作业,并且不能保证它将立即执行作业。