Search code examples
javaandroidalarmmanagerandroid-notificationsrepeatingalarm

Need some help to fill in the blanks in code that schedules daily notifications


I've searched through Android studio documentation and found some pieces of code that should schedule daily notifications. Unfortunately, as I'm new to all of this, it has some missing pieces that I can't figure out.

private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
...
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);

// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        1000 * 60 * 20, alarmIntent);

What is this "context" in context.getSystemService, new Intent(context, AlarmReceiver.class), etc.? Is there anything else missing that is not here?


Solution

  • Its the application context. To be clear it is the information and data of the current Activity you want to use(e.g. the MainActivity). You can get it with

    Context context = this.getApplicationContext();
    

    Edit: For the sake of more general usage