首页 文章

在Android O上使用JobScheduler启动服务

提问于
浏览
0

我正在尝试启动一个IntentService来注册Android O上的firebase Cloud 消息 .

在Android O上,不允许“在不允许的情况下”启动Intent Service,并且每个人都告诉我使用JobService而不是如何使用它 .

What constraints should the JobInfo.Builder have in order to have a "situation where it's permitted", i keep getting the same 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 回答

  • -1

    如果您使用的是支持库版本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());
    

    您需要为Oreo之前的设备添加此权限

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

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

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

    getApplicationContext().startService(intent);
    

    startService(intent);
    

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

相关问题