可能重复
我创建了JobDispatcher服务,以保持后台获取用户位置并将用户位置发布到服务器.为此,我创建了一个工作,如下所示:
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; }在服务的onStartJob中,我正在配置位置api以获取用户位置
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; }服务将启动,并按预期运行.但这并没有停止.我已经使用了两种方式(dispatcher.cancel和stopService)来停止服务,如下所示:
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(); }推荐答案
您需要通过注销位置侦听器并在LocationJobService中调用jobFinished()本身来取消作业.
you need to cancel job in itself by unregistering location listener and calling jobFinished() inside LocationJobService.
由于dispatcher.cancelAll()只能取消尚未运行的预定作业. 您可以使用Eventbus之类的工具通知服务何时停止.
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.
请参阅 medium. com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129 了解更多信息.
更多推荐
无法停止Firebase JobDispatcher服务
发布评论