机器人 - 运行后台任务,每15分钟,即使当应用程序没有运行 [英] Android - Running a background task every 15 minutes, even when application is not running

查看:220
本文介绍了机器人 - 运行后台任务,每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.

我看我可以使用某种形式的可运行()功能或使用后台服务或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?

推荐答案

您已经detemined的时间量(间隔)来执行的code的一个片段,它能够更好地使用的AlarmManager 的,因为它更多的能量effient。如果你的应用程序需要听一些排序的事件,那么服务就是你所需要的。

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

}

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

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