Best way to use TriggerEventListener in the background?

匆匆过客 提交于 2019-11-28 12:53:21

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/49532971/best-way-to-use-triggereventlistener-in-the-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!