在Android O上使用JobScheduler启动服务

时间:2018-04-23 16:35:34

标签: android firebase android-intentservice android-jobscheduler

我尝试启动IntentService以注册Android O上的firebase云消息。

在Android O上,不允许启动意图服务"在不允许的情况下"并且每个人都告诉我使用JobService而不是如何使用它。

JobInfo.Builder应该有什么约束才能有一个允许的情况",我一直得到相同的IllegalStateException

这是我的JobService

@Override
public boolean onStartJob(JobParameters params) {
    Intent intent = new Intent(this, RegistrationIntentService.class);
    getApplicationContext().startService(intent);
    return false;
}

@Override
public boolean onStopJob(JobParameters params) {
    return false;
}

public static void scheduleJob(Context context) {
    ComponentName serviceComponent = new ComponentName(context, MyJobService.class);
    JobInfo.Builder builder = new JobInfo.Builder(MyJobService.JOB_ID, serviceComponent);
    builder.setMinimumLatency(1 * 1000); // wait at least
    JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
    if(jobScheduler != null) jobScheduler.schedule(builder.build());
}

2 个答案:

答案 0 :(得分:6)

如果您使用的是支持库版本26.1.0或更高版本,则可以访问与JobIntentService类似的Intent Service,并具有作业调度程序的额外优势,您无需管理除了开始之外的任何事情。

根据文档

  

帮助处理已加入工作/服务的工作。在Android O或更高版本上运行时,工作将通过JobScheduler.enqueue作为作业分派。在旧版本的平台上运行时,它将使用Context.startService。

您可以在JobIntentService找到更多详情。

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;

public class JobIntentNotificationService extends JobIntentService {

    public static void start(Context context) {
        Intent starter = new Intent(context, JobIntentNotificationService.class);
        JobIntentNotificationService.enqueueWork(context, starter);
    }

    /**
     * Unique job ID for this service.
     */
    static final int JOB_ID = 1000;

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

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        // do your work here
    }
}

你打电话的方式是

JobIntentNotificationService.start(getApplicationContext());

您需要为此前奥利奥设备添加此权限

<!-- used for job scheduler pre Oreo -->
<uses-permission android:name="android.permission.WAKE_LOCK" />

答案 1 :(得分:-1)

Firebase实际上有一个专门的服务来接收名为FirebaseMessagingService的邮件。 This Firebase page应该包含所有信息,以帮助您在这方面开始。

除此之外,您应该尝试从服务访问应用程序上下文,而您应该使用父服务的基本上下文:

    getApplicationContext().startService(intent);

    startService(intent);

如果您想从FirebaseMessagingService启动某些工作,请查看他们的JobDispatcher库,这非常棒。