1

我需要在每天早上 5 点运行我的更新服务,以便在用户早上拿起手机时刷新数据。我到目前为止的代码是 -

Log.d(TAG, "setAutoRun");
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, RefreshIntentService.class);
PendingIntent pendingI = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar time = Calendar.getInstance();

time.setTimeInMillis(System.currentTimeMillis());

time.add(Calendar.SECOND, 60); // this was just to test out the alarm service
alarmMgr.set(AlarmManager.RTC, time.getTimeInMillis(), pendingI);

我该如何修改它以使其每天早上 5 点运行?我知道我可以设置一个间隔,以便它会在 X 分钟内再次运行,但是如果用户那时不打开它,我怎么能在早上 5 点开始它。

谢谢

4

2 回答 2

4

我相信Calendar params像这样编辑你应该可以工作并更改为setRepeating()

Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 5);   

alarmMgr.setRepeating(AlarmManager.RTC, time.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingI);

AlarmManager.INTERVAL_DAY

于 2013-04-03T19:47:12.430 回答
0

您可以使用 setRepeating 方法,在该方法中您可以通过特定时间。看这个例子:

private void scheduleAlarms() {
        Intent intent = new Intent(mContext, AlarmActivity.class);
        mPendMorInt = PendingIntent.getActivity(
                mContext, Constants.ALARM_MORNING_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        mPendAftInt = PendingIntent.getActivity(
                mContext, Constants.ALARM_AFTERNOON_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        List<Long> alarms = SelectorAlarm.timeAlarms(mContext);
        if (alarms.size() >= 1) {
            mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
            mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, getRightTimeAlarm(alarms.get(Constants.MORNING)),
                    AlarmManager.INTERVAL_DAY, mPendMorInt);
            mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, getRightTimeAlarm(alarms.get(Constants.AFTERNOON)),
                    AlarmManager.INTERVAL_DAY, mPendAftInt);
        }
    }
于 2013-04-03T19:52:55.897 回答