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

Dij*_*ark 19 java service android repeat

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

我怎么能做到这一点?我似乎无法绕过这个.

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

什么是更好的方法,我怎么能这样做?

wts*_*g02 23

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

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

}
Run Code Online (Sandbox Code Playgroud)

  • 是.警报管理器就像,你(应用程序)告诉操作系统,你想在X毫秒后做一些事情.然后系统在BroadcastReciever.onRecieve()中执行该代码,它是您希望在x毫秒后在后台执行的代码. (2认同)