Search code examples
androidalarmmanagermultiple-instancesandroid-broadcastreceiver

how to set multiple Alarm in android to perform time-based operations outside the lifetime of my application?


In the main activity of my application , there are two text field where the users insert date and time and a button start. When the button start is clicked , it is invokes the method setProgrammedTimer of the broadcastReceiver class that sets an alarm at date and time inserted by users and at these date and time, the application invokes the activity DIAL phone. But if i insert one date and one time and i click start button, and after i insert a new date and time and i click start button, the application run only the second alarm. how can i do to execute both alarms?

This the button start code on main activity:

 start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            year = Integer.valueOf(yearT.getText().toString());
            month = Integer.valueOf(monthT.getText().toString());
            day = Integer.valueOf(dayT.getText().toString());
            hour = Integer.valueOf(hourT.getText().toString());
            minute = Integer.valueOf(minuteT.getText().toString());
      timer.setProgrammedTimer(context,year,month,day,hour,minute);

This is the broadcastReceiver code:

public class TimerBroadcast extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
    wl.acquire();
    Intent callIntent = new Intent(Intent.ACTION_DIAL);
    callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(callIntent);
    wl.release();

}

public void setProgrammedTimer(Context context,int year, int month,int day, int hour, int minute){

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context,TimerBroadcast.class);
    PendingIntent pi = PendingIntent.getBroadcast(context,0,intent, PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.set(Calendar.YEAR,anno);
    cal.set(Calendar.MONTH,mese-1);
    cal.set(Calendar.DAY_OF_MONTH,giorno);
    cal.set(Calendar.HOUR_OF_DAY,ora);
    cal.set(Calendar.MINUTE,minuti);
    cal.set(Calendar.SECOND,0);
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
}

Solution

  • When you are adding second alarm you are cancelling the first.

    PendingIntent pi = PendingIntent.getBroadcast(context,0,intent, PendingIntent.FLAG_CANCEL_CURRENT);
    

    Note FLAG_CANCEL_CURRENT.