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

不羁岁月 提交于 2019-11-26 22:49:07

问题


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.

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?


回答1:


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

}



回答2:


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




回答3:


You can also achieve this via a SyncAdapter Here's a sample for your to look at and get inspired

SyncAdapter sample




回答4:


The best approach was introduced at Google I/O 2018 - WorkManager.

You can find documentation here.



来源:https://stackoverflow.com/questions/16155032/android-running-a-background-task-every-15-minutes-even-when-application-is-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!