简体   繁体   中英

Repetitive alarm using alarm manager

I am trying to make an alarm application that takes multiple "n" time inputs from the user and rings at those particular times. For that I have created an array of EditTexts for both the hour and minute entries. In the onclick listener for the start button, I wish to have alarm managers for all the entered time inputs initialized.

After creating an array of calendar, should i create an array of intents and pending intents and alarm manager objects also--one each for each calendar object?

This is the code for my start button:

public void setAlert(View view) {

    int length = editHour.length;
    int h[] = new int[length];
    int m[] = new int[length];
    Calendar[] cal = new Calendar[length];
    for (int i = 0; i < length; i++) {
        cal[i] = Calendar.getInstance();
    }
    for (int i = 0; i < length; i++) {
        try {

            m[i] = Integer.parseInt(editHour[i].getText().toString());

            h[i] = Integer.parseInt(editMinute[i].getText().toString());

            cal[i].set(Calendar.HOUR, h[i]);
            cal[i].set(Calendar.MINUTE, m[i]);

            Intent intent = new Intent(this, AlarmService.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP,
                    cal[i].getTimeInMillis(), pendingIntent);
            Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.print("OOPS!");

        }
    }
}

your request code is unique and this is your problem. you must use unique code for your different alarms. your code with one request code override alarm time. (sorry for my bad english, it is not my language!)

use this code:

for (int i = 0; i < length; i++) {
    .
    .
    .

    int requestCode = (int) (System.currentTimeMillis());
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
                requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    Thread.sleep(10);

    .
    .
    .
}

If you want 5 different alarms then your PendingIntent should be different. You can make a PendingIntent unique by putting an extra in it. but anyway, your code should at least generate one alarm. Verify that the time you are setting in the calendar is correct.

Anyway, you don't need 5 separate calendars, intents or anything. just update them and set the alarm. you definitively don't need to save them in an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM