我正在尝试在新应用程序中使用CommonsWare的WakefulIntentService,特别是它能够轻松安排意图服务以便以后运行。
我有一个PreferenceActivity,允许用户选择运行服务的计划(例如每天早上5点)。一旦用户更改了首选项值,我就会调用:
AutoDownloadIntentServiceAlarmListener alarmListener = new AutoDownloadIntentServiceAlarmListener();
alarmListener.setForcedHour(5); // we want to schedule alarm for 5am everyday.
WakefulIntentService.scheduleAlarms(alarmListener, this, true);
出于某种原因,所需的IntentService(扩展WakefulIntentService)会立即启动并执行其工作。
以下是AutoDownloadIntentServiceAlarmListener的实现:
public class AutoDownloadIntentServiceAlarmListener implements WakefulIntentService.AlarmListener {
private static final String TAG = "AutoDownloadIntentServiceAlarmListener";
private int mForcedHour = -1;
@Override
public long getMaxAge() {
return AlarmManager.INTERVAL_DAY * 2;
}
public void setForcedHour(int forcedHour) {
mForcedHour = forcedHour;
}
@Override
public void scheduleAlarms(AlarmManager alarmManager, PendingIntent pendingIntent, Context context) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
String autoDownloadTimePref = MyApplication.getInstance().getPrefs().getString("autoDownloadEpisodesSchedule", "0");
int hourOfAlarm = Integer.parseInt(autoDownloadTimePref);
// if this class has been created with a specific hour
// use it instead of the value obtained from SharedPreferences above.
if (mForcedHour > -1) {
Log.w(TAG, "Forced hour has been set for this AlarmListener. " + mForcedHour);
hourOfAlarm = mForcedHour;
}
calendar.set(Calendar.HOUR_OF_DAY, hourOfAlarm);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d(TAG, String.format("Scheduled inexact alarm for %d", hourOfAlarm));
}
@Override
public void sendWakefulWork(Context context) {
Intent serviceIntent = new Intent(context, AutoDownloadIntentService.class);
WakefulIntentService.sendWakefulWork(context, serviceIntent);
}
}
我的意图是服务不会在安排后立即启动,而是在第二天凌晨5点启动。 (并继续无限期地重复此计划,或直到用户选择禁用或更改其计划)
我做错了什么?
答案 0 :(得分:3)
我的意图是服务不会在安排后立即启动,而是在第二天凌晨5点启动。
除了这不是你的代码所做的,大约80%的时间。您的代码表示它应该在今天凌晨5点运行,因为您获得当前时间而不是更改当天。大部分时间,今天凌晨5点都是过去,所以AlarmManager
将立即开始工作。
您需要查看计算出的Calendar
是否比现在更早,如果是,请添加一天。