Search code examples
androidbroadcastreceiveralarmmanager

how to set multiple alarms using sqlite data?


I am new to android ,here I am developing an alarm app for my working knowledge .

I have completed the following :

  • creating alarms and storing it into sqlite database.
  • Fetching all the alarms which has the status as active .

I have tried many stackoverflow post and their solutions and other blog posts which related to my doubt but I can't get a solution for my problem .

What is my problem is I am receiving number of alarm timings from sqlite database which I have set it before and I want to set all the alarms on the stored time .

Here I don't know how to set it .

Can anyone help me to set the multiple alarms .

I am really looking for someone's help to learn and experience these things please help me .

Thanks.


Solution

  • You need Alarm Manager and Pending Intent more.

    for (int i = 0; i < ActivemyAlarms.size(); i++) {
    
                int mHour = 0,mMin=0;
                String amPm = null;
                int mAlarmId = ActivemyAlarms.get(i).getALARM_ID(); //each alarm has an unique Id ,for differentiate one from another
                String mAlarmTime = ActivemyAlarms.get(i).getALARM_TIME(); // alarm time (11:12:AM)
    
    
                if (!(mAlarmTime == null)) {
                    String mtime = mAlarmTime;  // alarm time format is 12hr format (ex : 11:12:AM)
                    String[] time = mtime.split(":");
                    mHour = Integer.parseInt(time[0].trim()); // get 11 hour
                    mMin = Integer.parseInt(time[1].trim()); // get 12 min
                    amPm = ((time[2].trim()));
                }
                Calendar calendar = Calendar.getInstance();
                calendar.set(calendar.HOUR_OF_DAY, amPm!=null && amPm.equalsIgnoreCase("pm")?(mHour+12):mHour);
                calendar.set(calendar.MINUTE, mMin);
                calendar.set(calendar.SECOND, 0);
                calendar.set(calendar.MILLISECOND, 0);
    
                Intent intent = new Intent(this,AlarmReceiver.class); //calling my Alarm service class which plays a music on the specific time
                final int _id = (int) System.currentTimeMillis(); // get calendar instance
    
                //Use Alarm manager and Pending Intent
    
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mAlarmId, intent, 0);
    
                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
    

    }

    And to cancel any Alarm call alarmManager.cancel(PendingIntent) like;

    Intent intent = new Intent(this,AlarmReceiver.class);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mAlarmId, intent, 0);
    alarmManager.cancel(alarmIntent);