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計算結果が現在よりも古いかどうかを確認する必要があります。古い場合は、1 日追加します。

于 2013-01-21T12:41:23.430 に答える