简体   繁体   English

Android - 每 15 分钟运行一次后台任务,即使应用程序未运行

[英]Android - Running a background task every 15 minutes, even when application is not running

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

How can I accomplish this?我怎样才能做到这一点? I can't seem the wrap my head around this.我似乎无法解决这个问题。

I read I could use some sort of runnable() functionality or use a background services or AlarmManager.我读到我可以使用某种 runnable() 功能或使用后台服务或 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?有什么更好的方法可以做到这一点,我该怎么做?

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.您已经确定了执行一段代码的时间(间隔),最好使用AlarmManager,因为它更节能。 If your app needs to listen to some sort of a event , then Service is what you need.如果您的应用程序需要侦听某种事件,那么 Service 就是您所需要的。

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

}

Alarm Manager (system service) vs Remote Service with inner alarm implementation (separate process)?警报管理器(系统服务)与具有内部警报实现(单独进程)的远程服务?

Alarm Manager is your choice, because it already has what you need, you just have to set alarm intervals闹钟管理器是你的选择,因为它已经有你需要的东西,你只需要设置闹钟间隔

You can also achieve this via a SyncAdapter Here's a sample for your to look at and get inspired您还可以通过 SyncAdapter 实现此目的这是一个示例,供您查看并获得启发

SyncAdapter sample 同步适配器示例

Work manager is actually the best thing to do with periodically repeat, their default is 15 minutes which exactly like you need.工作经理实际上是定期重复的最佳选择,他们的默认值是 15 分钟,这完全符合您的需要。 Here is an example:下面是一个例子:

        final PeriodicWorkRequest periodicWorkRequest
                = new PeriodicWorkRequest.Builder(ApiWorker.class, 15, TimeUnit.MINUTES)
                .build();
        WorkManager.getInstance().enqueue(periodicWorkRequest);

Where ApiWorker is just the following class:其中 ApiWorker 只是以下类:

public class ApiWorker extends Worker implements iOnApiRequestSuccessful {

public ApiWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {
    return Result.success();
}
}

And fill whatever work you want to be done in the doWork() function before the return with success.并在成功返回之前在 doWork() 函数中填写您想要完成的任何工作。

Return.success() makes it inserted to the queue again so it will be repeated every 15 minutes. Return.success() 使它再次插入到队列中,因此它将每 15 分钟重复一次。

The best approach was introduced at Google I/O 2018 - WorkManager .最好的方法是在 Google I/O 2018 - WorkManager 上介绍的

You can find documentation here .您可以在此处找到文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM