Cant stop Firebase JobDispatcher service

有些话、适合烂在心里 提交于 2019-12-02 06:46:01

问题


Possible Duplicate

I have created a JobDispatcher service to keep getting user location in background and post user location to server. For that i have created a Job as follow:

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;
    }

In service's onStartJob i am configuring location api to get user location

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

Service starts and keep running as expected. But it does not stop. I have used both ways (dispatcher.cancel and stopService) to stop service as follow:

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:


you need to cancel job in itself by unregistering location listener and calling jobFinished() inside LocationJobService.

As dispatcher.cancelAll() works only to cancel scheduled jobs which are yet to be run. You may use tools like Eventbus to inform service when to stop.

Refer https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129 for more info.



来源:https://stackoverflow.com/questions/51780753/cant-stop-firebase-jobdispatcher-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!