0

我正在尝试在新应用程序中使用 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 点启动。(并继续无限期地重复此计划,或直到用户选择禁用或更改其计划)

我究竟做错了什么?

4

1 回答 1

3

我的意图是该服务不会在预定后立即启动,而是仅在第二天早上 5 点启动。

除非这不是您的代码所做的,大约 80% 的时间。您的代码说它应该在今天早上 5 点运行,因为您正在获取当前时间而不是更改日期。大多数时候,今天凌晨 5 点已经过去,因此AlarmManager会立即开始工作。

您需要查看您的计算Calendar是否比现在更早,如果是,请添加一天。

于 2013-01-21T12:41:23.430 回答