问题
I am using work manager to start location services, it loads doWork()
method after every 15 minutes
, but does not execute onLocationChanged
.
Before i was using Job Scheduler, and it was working just fine.
The following code also works fine, if i display notification from Work Manager after 15 minutes.
This is my code.
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;
//...
}
回答1:
There are a few things that are wrong with this code:
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).
You are returning null from a @NonNull method. WorkManager will immediately treat this work as failed. Return a proper value.
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.
来源:https://stackoverflow.com/questions/55795134/location-not-getting-called-from-workmanager