Android alarmmanager在特定日期设置警报并在几周内重复它们

时间:2016-07-12 17:36:18

标签: android android-studio alarmmanager alarms

我制作了一个可以设置闹钟的应用。它实际上只有一次有效。 而且我需要不止一次。我试着做一个班级安排警报。

例如我七点钟的星期一,所以我需要每个星期一开始闹钟。但是我星期二还有另一节课,必须这样做。

这是我的代码,工作pd-> rqs1 = 1

Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        cal.set(Calendar.HOUR_OF_DAY, horai); // i put the hour with the interface
        cal.set(Calendar.MINUTE,minutoi);///
       cal.set(Calendar.DAY_OF_WEEK,dias.getSelectedItemPosition()+1);
        cal.add(Calendar.SECOND, 2);



        Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
        intent.putExtra("name", curso); // i put the name of the curso
      PendingIntent pendingIntent =
               PendingIntent.getBroadcast(getBaseContext(),
                      RQS_1, intent, PendingIntent.FLAG_ONE_SHOT);


    AlarmManager alarmManager =
            (AlarmManager)getSystemService(Context.ALARM_SERVICE);


    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), 24 * 7 * 60 * 60 * 1000 , pendingIntent);`

所以,我一直在寻找如何做到这一点。 请帮我 。感谢

2 个答案:

答案 0 :(得分:0)

尝试使用 FLAG_UPDATE_CURRENT 代替 FLAG_ONE_SHOT

还要确保在设备重启后重新安排闹钟。 Here就是一个很好的例子。

答案 1 :(得分:0)

1 - 替换此

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
        cal.getTimeInMillis(), 24 * 7 * 60 * 60 * 1000 , pendingIntent);`

用这个:

alarmManager.set(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), 24 * 7 * 60 * 60 * 1000 , pendingIntent);

2 - 替换此

PendingIntent pendingIntent =
           PendingIntent.getBroadcast(getBaseContext(),
                  RQS_1, intent, PendingIntent.FLAG_ONE_SHOT);

用这个:

PendingIntent pendingIntent =
           PendingIntent.getBroadcast(getBaseContext(),
                  RQS_1, intent, PendingIntent.FLAG_UPDATE_CURRENT );

3 - onReceive

中添加此内容
  Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    intent.putExtra("name", curso); // i put the name of the curso
  PendingIntent pendingIntent =
           PendingIntent.getBroadcast(getBaseContext(),
                  RQS_1, intent, PendingIntent.FLAG_UPDATE_CURRENT );


AlarmManager alarmManager =
        (AlarmManager)getSystemService(Context.ALARM_SERVICE);


alarmManager.set(AlarmManager.RTC_WAKEUP,
        cal.getTimeInMillis(), 24 * 7 * 60 * 60 * 1000 , pendingIntent);`