Android - 每 15 分钟运行一次后台任务,即使应用程序未运行 [英] Android - Running a background task every 15 minutes, even when application is not running

查看:22
本文介绍了Android - 每 15 分钟运行一次后台任务,即使应用程序未运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建一个每 10/15 分钟运行一次的后台任务(并不重要,两者都很好),即使应用程序没有运行.

I need to build a background task that runs every 10/15 minutes (doesn't really matter, either is good), even when the application is not running.

我怎样才能做到这一点?我似乎无法理解这一点.

How can I accomplish this? I can't seem the wrap my head around this.

我读到我可以使用某种 runnable() 功能或使用后台服务或 AlarmManager.我在考虑后台服务,因为它也必须在应用程序本身未运行时完成.

I read I could use some sort of runnable() functionality or use a background services or AlarmManager. I was thinking of a background service, since it also must be done when the application itself is not running.

有什么更好的方法可以做到这一点,我该怎么做?

What is a better way of doing this and how could I do it?

推荐答案

您已经确定了执行一段代码的时间(间隔),最好使用 AlarmManager 因为它更节能.如果您的应用需要侦听某种事件,那么 Service 就是您所需要的.

You have have detemined the amount of time (interval) to execute a snippet of code, its better to use AlarmManager because its more energy effient. If your app needs to listen to some sort of a event , then Service is what you need.

public static void registerAlarm(Context context) {
    Intent i = new Intent(context, YOURBROADCASTRECIEVER.class);

    PendingIntent sender = PendingIntent.getBroadcast(context,REQUEST_CODE, i, 0);

    // We want the alarm to go off 3 seconds from now.
    long firstTime = SystemClock.elapsedRealtime();
    firstTime += 3 * 1000;//start 3 seconds after first register.

    // Schedule the alarm!
    AlarmManager am = (AlarmManager) context
            .getSystemService(ALARM_SERVICE);
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
            600000, sender);//10min interval

}

这篇关于Android - 每 15 分钟运行一次后台任务,即使应用程序未运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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