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

查看:23
本文介绍了在后台使用 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.

最好的方法是什么?

推荐答案

您可以使用 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;
    }
}

你可以像这样配置它

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天全站免登陆