在后台使用TriggerEventListener的最佳方法? [英] Best way to use TriggerEventListener in the background?

查看:128
本文介绍了在后台使用TriggerEventListener的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望制作一个在后台运行的应用程序,记录位置数据,而无需用户实际将应用程序放在前台,但同时不会消耗太多电池.

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.

我本来以为将BOOT_COMPLETED设置为BroadcastReceiver并运行一项服务,该服务在每次触发时使用有意义的运动"传感器记录位置数据,但是自奥利奥(Oreo)以来,对后台服务存在很多限制.

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?

推荐答案

您可以使用JobService在电池和现代方式方面都很有效,可以在后台执行任务.

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

这篇关于在后台使用TriggerEventListener的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆