I'm looking to make an application that runs in the background, logging location data without the user actually having to have the application in the foreground but at the same time doesn't use too much battery.
I originally thought of setting a BroadcastReceiver for BOOT_COMPLETED and run a service which uses a Significant Motion sensor to log location data whenever the it fired off, but ever since Oreo, there are alot of limitations on background services.
What is the best way to do this?
You can use JobService
it's efficient in terms of battery and modern way to perform the task in the background.
public class YourJobService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
if (!Utility.isServiceRunning(GetAlertService.class, getApplicationContext())) {
startService(new Intent(getApplicationContext(), GetAlertService.class));
}
jobFinished(params, false);
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
return true;
}
}
and you can configure it the way you want it like this
ComponentName getAlertJobComponent = new ComponentName(context.getPackageName(), YourJobService.class.getName());
JobInfo.Builder getAlertbuilder = new JobInfo.Builder(Constants.getAlertJobid, getAlertJobComponent);
getAlertbuilder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); // require unmetered network
getAlertbuilder.setRequiresDeviceIdle(true); // device should be idle
getAlertbuilder.setPeriodic(10 * 1000);
getAlertbuilder.setRequiresCharging(false); // we don't care if the device is charging or not
JobScheduler getAlertjobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
getAlertjobScheduler.schedule(getAlertbuilder.build());
For more detail refer this Intelligent Job-Scheduling