安排服务每半小时执行一次

Schedule a service for execute every half hour

我编写了一个代码,用于在我的应用程序关闭时每半小时启动一次服务:

Intent serviceIntent = new Intent(context, BackgroundService.class);
pIntent = PendingIntent.getService(context, 0, serviceIntent, 0);
alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    AlarmManager.INTERVAL_HALF_HOUR, AlarmManager.INTERVAL_HALF_HOUR, pIntent);

BackGround服务扩展了IntentService,从服务器下载一些数据,如果验证了某些条件,则在通知栏上显示通知。

但碰巧当我关闭我的应用程序时,服务会立即执行,而不是在半小时后。 我如何更正我的代码以在半小时后首次执行?

But it happen that service is executed immediatly when i close my app, and not after half hour.

setInexactRepeating() 的第二个参数是您希望事件首次发生的时间。当使用 ELAPSED_REALTIMEELAPSED_REALTIME_WAKEUP 时,需要表示为 SystemClock.elapsedRealtime()+...,其中 ... 是您希望事件发生的距离现在 (SystemClock.elapsedRealtime()) 的距离以毫秒为单位。您的代码不会这样做;你想要的开始时间是过去的时间。