First of all, I'm a total Android noob. Have looked for solutions for some time now, but can't find any helpful hints in the right direction so far. This might be generally caused by the nature of the issue itself, being quite niche.
The working code below is based on a code lab at https://codelabs.developers.google.com/codelabs/realtime-asset-tracking.
I was wondering though, since it was mentioned within several resources as the preferred way now, how you'd do something like that based on Android's Work Manager instead of a Service with an ongoing notification?
public class TrackerService extends Service {
@Override
public void onCreate() {
super.onCreate();
requestLocationUpdates();
}
private void requestLocationUpdates() {
LocationRequest request = new LocationRequest();
request.setInterval(5 * 60 * 1000);
request.setFastestInterval(30 * 1000);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (permission == PackageManager.PERMISSION_GRANTED) {
client.requestLocationUpdates(request, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location location = locationResult.getLastLocation();
if (location != null) {
Log.d(TAG, "location update " + location);
}
}
}, null);
}
}
}
With my experience from web projects the above code establishes a "listener" based on the FusedLocationProviderClient. As soon as there's a new location update, it would call onLocationResult
with the respective location result.
What I found out about the Work Manager so far is that you can set up a Worker with Work Manager to doWork()
once or periodically. Effectively like a cron job...
What I don't understand, if there's no running service in the background where would the Worker and the request for location updates be initiated? And how would they work together?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…