gpt4 book ai didi

android - 无法停止 Firebase JobDispatcher 服务

转载 作者:行者123 更新时间:2023-11-29 18:46:15 26 4
gpt4 key购买 nike

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

最佳答案

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

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

引用https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129了解更多信息。

关于android - 无法停止 Firebase JobDispatcher 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51780753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com