I would like to implement a tracking app which requests the current user position every 3 minutes. The app should run in background (also when the app is closed). Currently I am trying to use a WorkManager for it. Unfortunately I do not get the GPS position (Toast Message) when the app is closed.
My code:
public class LocationWorker extends Worker {
private FusedLocationProviderClient client;
public LocationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
requestLocationUpdates();
return null;
}
private void requestLocationUpdates() {
LocationRequest request = new LocationRequest();
request.setInterval(5 * 1000);
request.setFastestInterval(5 * 1000);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
client = LocationServices.getFusedLocationProviderClient(getApplicationContext());
int permission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
if (permission == PackageManager.PERMISSION_GRANTED) {
final LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Toast.makeText(getApplicationContext(),"TEST",Toast.LENGTH_LONG).show();
Location location = locationResult.getLastLocation();
if (location != null) {
Log.e("LONG", "location update " + location.getLongitude());
}
}
};
client.requestLocationUpdates(request, locationCallback,Looper.getMainLooper());
}
}
Any idea what I should do to receive the location updates in background when the app is closed? And should I use WorkManager or is something else a better solution? I also tried the PeriodicWorkRequest but it had a minimum interval (15 min).