无法从WorkManager调用位置 [英] Location not getting called from WorkManager
问题描述
我正在使用工作管理器启动位置服务,它每隔 15分钟
就会加载 doWork()
方法,但是不执行 onLocationChanged
.
I am using work manager to start location services, it loads doWork()
method after every 15 minutes
, but does not execute onLocationChanged
.
在我使用Job Scheduler之前,它工作得很好.
Before i was using Job Scheduler, and it was working just fine.
如果我在15分钟后显示来自工作管理器的通知,则以下代码也可以正常工作.
The following code also works fine, if i display notification from Work Manager after 15 minutes.
这是我的代码.
public class LocationWorker extends Worker implements LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private static final long BACKGROUND_INTERVAL = 1000 * 60 * 60;
final private String TAG = LocationUpdateService.class.getSimpleName();
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
@NonNull
@Override
public Result doWork() {
if (isGooglePlayServicesAvailable()) {
mGoogleApiClient = new GoogleApiClient.Builder(GlobalApplication.getAppContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
jwtToken = getJWTToken();
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(BACKGROUND_INTERVAL);
mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
return null;
}
@Override
public void onLocationChanged(Location location) {
String storedLat, storedLng;
//...
}
推荐答案
此代码有一些错误之处:
There are a few things that are wrong with this code:
-
从总体上讲,您正在使用一个同步的Worker来执行异步(基于回调)的代码.这行不通.请阅读 https://developer.android.com/topic/libraries/体系结构/工作管理器/高级/线程处理(尤其要注意ListenableWorker,这是您要使用的类).
At a high level, you are using a Worker - which is synchronous - to execute an asynchronous (callback-based) piece of code. This won't work. Please read https://developer.android.com/topic/libraries/architecture/workmanager/advanced/threading (and in particular, pay attention to ListenableWorker - that's the class you want to use).
您正在从@NonNull方法返回null.WorkManager将立即将此工作视为失败.返回正确的值.
You are returning null from a @NonNull method. WorkManager will immediately treat this work as failed. Return a proper value.
您的位置间隔设置为一个小时.工人们最多可以执行10分钟,因此这也不起作用.FWIW,我真的很怀疑这段代码是否与JobScheduler一起正常工作.它也有一个10分钟的执行窗口.
Your location interval is set for an hour. Workers can execute for a maximum of 10 minutes, so this won't work either. FWIW, I really doubt this code was working properly with JobScheduler; it too has a 10 minute execution window.
这篇关于无法从WorkManager调用位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!