Android SDK - 设置具有相同 Intent 不同附加功能的多个警报

Android SDK - Set multiple alarms with same Intent different extras

我试图让 2 个重复警报触发相同的 Intent 但具有不同的额外功能:

// first alarm @ 2AM
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY, 2);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);

// second alarm @ 3AM
Calendar calendar2 = Calendar.getInstance();
calendar2.set(Calendar.HOUR_OF_DAY, 3);
calendar2.set(Calendar.MINUTE, 0);
calendar2.set(Calendar.SECOND, 0);

// Set both intents with differing extras
Intent intent1 = new Intent(context, Receiver.class);
intent1.putExtra("status", true);
Intent intent2 = new Intent(context, Receiver.class);
intent2.putExtra("status", false);

// Set both pending Intents with differint ids
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 1, intent1, 0);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 2, intent2, 0);

AlarmManager alarm1 = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm1.setRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pendingIntent1);
AlarmManager alarm2 = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm2.setRepeating(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pendingIntent2);

这是 Intent 触发的内容

public class Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("MyApp", "Received intent with status : " + intent.getBooleanExtra("status", false));
    }
.....
}

但是由于一个奇怪的原因,两个 Intent 都在凌晨 3 点左右被触发:

Received intent with status : false

Received intent with status : true

我做错了什么?

问题是 AlarmManager.setRepeative 与官方文档中写的不准确。

我在 2:50AM 开始我的程序所以使用上面的代码,第一个警报应该在 50 分钟前开始所以它需要被触发但是由于另一个警报被安排在 31M,Android OS 决定等待凌晨 3 点警报同时触发(我猜是为了降低电池消耗)。

解决方案是在需要时为警报添加 24 小时,以确保它们是在未来而不是过去安排的,并使用 AlarmManager.setExact,这是准确但不重复的。然后每天重新安排一个新的AlarmManager.setExact

如果您需要比 1 小时更高的准确性,我建议永远不要使用 AlarmManager.setRepeative