我一直在玩,AlarmManager
以便IntentService
在特定时间段后安排要执行的 X 任务。到目前为止它工作得很好,这里'我是如何做到的:
public static void scheduleNextRefresh (final Context context, long msFromNow) {
Constants.logMessage("Scheduling fetcher alarm to happen within: " + msFromNow/(1000*60) + " minutes");
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra(AlarmReceiver.EXTRA_ACTION, AlarmReceiver.FETCH_NEWS);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (msFromNow != -1) {
Constants.logMessage("Alarm set");
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + msFromNow, pendingIntent);
}
}
到目前为止,效果很好;但是,我通常只使用小间隔,例如 30 分钟或几个小时。
现在我想安排一个动作在未来几天发生,我很好奇它是否可以与 一起正常工作,或者使用另一个工具在 X 时间AlarmManager
发送 a 是否更简单。PendingIntent
由于最小的间隔是 3 天,并且在此过程中可能会有几次重启(我知道我自己每天至少重启一次手机),我不确定这AlarmManager
会有多实用。
首先,我使用的计划刷新的逻辑与上面发布的相同,唯一的区别是我添加了更多代码BroadcastReceiver
,以便在android.permission.RECEIVE_BOOT_COMPLETED
适当的情况下侦听和重新安排警报。
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
...some other code
else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Constants.logMessage("Re-scheduling alarms after boot completed");
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
//get the current interval we are using for cleanups
long alarmInterval = Long.valueOf(mPreferences.getString("pref_key_ccleaner_interval", "259200000"));
//get the last time in miliseconds that we set an alarm
//Whenever I schedule an alarm in the IntentService
//I store the time in ms to know when it was last scheduled
long lastAlarm = mPreferences.getLong(CacheCleaner.KEY_LAST_ALARM, 0);
if (lastAlarm == 0) {
//If no previous alarm is set, schedule it normally
CacheCleaner.scheduleNextCleanup(context, alarmInterval);
}
else {
//If there was an alarm set previously
//The difference between the alarmInterval and the amount of ms ellapsed since last alarm
//is the new time we will schedule this for
CacheCleaner.scheduleNextCleanup(context, (alarmInterval - (System.currentTimeMillis() - lastAlarm)));
}
}
我认为这可以解决问题,但我只是好奇有没有更好的方法来安排几天后发生的事件,而不必担心重新安排或其他事件。
有任何想法吗?