Islam Assem
Islam Assem

Reputation: 1512

Best practice for background task execute at fixed interval of 10 minutes

I have an app for managing employees and need to track their location at fixed interval of 10 minutes during work hours what is the best solution for this work manager,services or job scheduler i already tried services but when app is forced close it doesn't run and lose employee location

Upvotes: 0

Views: 580

Answers (1)

Mayuri Khinvasara
Mayuri Khinvasara

Reputation: 1517

For tracking location periodically,

Approximately for X mins - Recommended way :

  1. Use Fused Location provider and set time appropriately. It gives you location update callbacks frequently and is Android's recommended way of getting location. Set your interval using this

  2. Ensure you have location permission. Invoke location permission dialog if you don't have permission

Exact for X mins

  1. Use sticky foreground service to track location continuously without your app getting killed. Check sample here

See Example below

For Fused Location provider

@Override
protected void onResume() {
    super.onResume();
    if (requestingLocationUpdates) {
        startLocationUpdates();
    }
}

private void startLocationUpdates() {
    fusedLocationClient.requestLocationUpdates(createLocationRequest,
            locationCallback,
            Looper.getMainLooper());
}

Create your location request parameters as below :

protected static LocationRequest createLocationRequest() {

            LocationRequest mLocationRequest = LocationRequest.create();
            mLocationRequest.setInterval(LOCATION_UPDATE_TIME_INTERVAL_MINS * 60 * 1000);
            mLocationRequest.setFastestInterval(LOCATION_UPDATE_FATEST_TIME_INTERVAL_MINS * 60 * 1000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
            return mLocationRequest;
        }

Check detailed documentation for Receive periodic location updates here

Posting from Commonsware answer here : When doing stuff periodically in the background — JobScheduler, WorkManager, AlarmManager, FCM push messages, etc. — you have to take into account that your process might not be around when it is time for you to do your work. Android will fork a process for you, but it is "starting from scratch". Anything that your UI might have set up in memory, such as a database, would have been for some prior process and might not be set up in the new process.

Upvotes: 1

Related Questions