Android如何创建多个警报AlarmClock.ACTION_SET_ALARM

时间:2014-01-18 13:40:31

标签: android android-intent android-alarms

您好我正在尝试创建多个闹钟。 我得到当天剩下的小时数,除以所需的闹钟数,然后尝试设置它们之间的间隔闹钟。

因此,例如,如果警报数量为2,用户在14:00点击按钮还剩10小时,那么10小时/ 2次警报=每次警报之间的距离为5小时

所以我想设置2个闹钟(一个闹钟在19:00,另一个闹钟在24:00)

目前我的代码只设置了1个警报,似乎忽略了多次运行for循环。我不确定为什么for循环dosnt会创建多个警报

        try {
            // Current Time
            Time timeNow = new Time();
            timeNow.setToNow();
                int timeNowHour = timeNow.hour;
                int timeNowMins = timeNow.minute;

            // Hours left in day
                int hoursInADay = 24;
                int hoursLeftInDay = hoursInADay - timeNowHour;

            // Number of alarms
                int numAlarms = 2;

            // Calc time between each alarm
                int alarmDistance = hoursLeftInDay / numAlarms;

            for(int i = 0; i < numAlarms; i++){
                int alarmHour = timeNowHour + alarmDistance * (i+1);
                Intent alarmIntent = new Intent(AlarmClock.ACTION_SET_ALARM);
                alarmIntent.putExtra(AlarmClock.EXTRA_MESSAGE, "TEST ALARM");
                alarmIntent.putExtra(AlarmClock.EXTRA_HOUR, alarmHour);
                alarmIntent.putExtra(AlarmClock.EXTRA_MINUTES, timeNowMins);
                alarmIntent.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
                alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(alarmIntent);
            }
        } catch (Exception e) {
        }

由于

1 个答案:

答案 0 :(得分:0)

AlarmManager alarmManager= (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent intent=createPendingResult(ALARM_TIME_ID, new Intent(), 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,SystemClock.elapsedRealtime() + alarmDistance,alarmDistance, intent);

在onActivityMethod中你可以做任何你想做的事。 例如:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ALARM_TIME_ID) {
Toast.makeText(this, "Alarm is running", Toast.LENGTH_LONG).show();
}

确保将ALARM_TIME_ID设置为唯一的int值。