Search code examples
androidalarmmanager

How to create a certain number of variables where the number depends on User Input?


So I need to create a certain number of alarms. If the user needs 10 alarms at regular intervals throughout the day, how can I efficiently write my code so that I make 10 alarms?

Or, is it possible to overwrite a single alarm multiple times?

This is in regards to Android App Dev.


Solution

  • Is the choice of number of alarms left to the user? If yes,

    • Make a user interface (in your activity) for the user itself to add new alarm or give the number of alarms.
    • Declare an Alarm and instantiate a new object for each user request while maintaining the total number of alarms and change all the time for each accordingly.

    // context variable contains your `Context`
        AlarmManager mgrAlarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
        int[] TimeForAlarm = new int[UserInput];
        // Set the time for each alarm according to your need and UserInput.
        for(i = 0; i < UserInput; ++i)
        {
           Intent intent = new Intent(context, OnAlarmReceiver.class);
           // Loop counter `i` is used as a `requestCode`
           PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent, 0);
           // Single alarms according to time we have in TimeForAlarm.
           mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
                        TimeForAlarm[i], 
                        pendingIntent); 
    
           intentArray.add(pendingIntent);
        }
    

    This will create 'UserInput' number of alarms as times according to TimeForAlarm array. At the end intentArray will have all the pending intents (if you need them).