无法停止Firebase JobDispatcher服务

时间:2018-08-10 06:59:33

标签: android android-service firebase-job-dispatcher

Possible Duplicate

我创建了JobDispatcher服务,以保持在后台获取用户位置并将用户位置发布到服务器。为此,我创建了一个工作,如下所示:

private void startLocationJobService() {
        // Check if location job service already running
        if(!isMyServiceRunning(LocationJobService.class)) {
            Context context = config.getActivity();
            FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
            Job job = dispatcher.newJobBuilder()
                    .setLifetime(Lifetime.FOREVER)
                    .setService(LocationJobService.class)
                    .setTag(JOB_SERVICE_TAG)
                    .setReplaceCurrent(true)
                    .build();

            //creating new job and adding it with dispatcher
            dispatcher.mustSchedule(job);
        }
    }

private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) config.getActivity().getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

在服务的onStartJob中,我正在配置位置api以获取用户位置

public boolean onStartJob(final JobParameters job) {
        Log.i("TAG", "Service Run onStartJob called");
        configureFusedLocation(LocationJobService.this);
        return true;
    } 

服务将启动,并按预期运行。但这并没有停止。我已经使用了两种方式(dispatcher.cancel和stopService)来停止服务,如下所示:

public void stopService() {
        if(isMyServiceRunning(LocationJobService.class)) {
            config.getActivity().stopService(new Intent(config.getActivity(), LocationJobService.class));
            cancelLocationJobService();
        }
    }

private void cancelLocationJobService(){
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(config.getActivity()));
        // Cancel the job for this tag
        dispatcher.cancel(JOB_SERVICE_TAG);
        //Cancel all the jobs for this package
        dispatcher.cancelAll();
    }

1 个答案:

答案 0 :(得分:2)

您需要通过注销位置侦听器并在LocationJobService中调用jobFinished()本身来取消作业。

dispatcher.cancelAll()仅用于取消尚未运行的预定作业。 您可以使用Eventbus之类的工具来通知服务何时停止。

有关更多信息,请参考https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129