Pritesh Pritesh - 1 year ago 166
Android Question

More than one alarms in alarmManager

This is an sms timer app so i need to set multiple alarms using alarm manager so that i can send messages to many people.
my code is :

Phone = phone.getText().toString();
Message = message.getText().toString();
//Validating if any field empty
if (Phone.length() >= 10 && Message.length() > 0) {
Toast.makeText(this.getApplicationContext(), "Your sms will be sent soon", Toast.LENGTH_SHORT).show();
//Getting Calender Reference
Calendar cal = Calendar.getInstance();
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
if (currentApiVersion > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
cal.set(Calendar.MINUTE, time_picker.getMinute());
cal.set(Calendar.HOUR_OF_DAY, time_picker.getHour());
} else {
//Setting the date and time from the time picker
cal.set(Calendar.MINUTE, time_picker.getCurrentMinute());
cal.set(Calendar.HOUR_OF_DAY, time_picker.getCurrentHour());

int a = (Calendar.getInstance().get(Calendar.SECOND) * 1000);

myIntent = new Intent(this, MyReceiver.class);
//Pending Intent for sending the intent afterwards
pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, myIntent, 0);
alarmManager = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
alarmManager.set(AlarmManager.RTC, cal.getTimeInMillis() - a, pendingIntent);

All the code in in an onclick function, so when the user fills the data and clicks send it should set an alarm.
I only need at most 5 alarms.
I tries creating
but it didnt work, only the latest alarm is getting set.

Answer Source

PendingIntents are usually difrenciated by their requestCode (works like an ID), that may be what's causing your problem, you can set the requestCode like this:

Add this outside of onCreate:

static int i; 

and replace this:

pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, myIntent, 0);

with this:

pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), i++ /*this number is the PendingIntent's requestCode*/, myIntent, 0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download