简体   繁体   中英

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();
        phone.setText("");
        message.setText("");
        //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 AlarmManager[] and ArrayList<PendingIntent> but it didnt work, only the latest alarm is getting set.

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);

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