我正在寻找一个在后台运行的应用程序,记录位置数据,而用户实际上不必将应用程序放在前台,但同时不会使用太多电池。
我最初想过为BOOT_COMPLETED设置一个BroadcastReceiver并运行一个服务,该服务使用一个重要的运动传感器来记录位置数据,但是自从奥利奥以来,背景服务有很多限制。
这样做的最佳方式是什么?
答案 0 :(得分:1)
您可以使用JobService
高效的电池和现代方式在后台执行任务。
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;
}
}
你可以按照你想要的方式配置它
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());
有关详细信息,请参阅此Intelligent Job-Scheduling