Search code examples
javaandroidnotificationsandroid-notificationsandroid-timepicker

Send notification at specific time


I've been trying to send a notification on a specific time. I've got the time input from user like this:

currentTimeHour = new Time(System.currentTimeMillis()).getHours();
currentTimeMinute = new Time(System.currentTimeMillis()).getMinutes();

TimePickerDialog dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker timePicker, int i, int i1) {
        hour = i;
        minute = i1;
    }
}, currentTimeHour, currentTimeMinute, false);

Now I want to send a notification on the specific Hour & minute given by user via TimePickerDialog. But I'm stuck...

A full solution would be very appreciated...


Solution

  • Everyone is telling you to use Alarm Manager class but there is no example code provided. Here is one of my implementation.

        AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 02);
        calendar.set(Calendar.MINUTE, 00);
    
    // setRepeating() lets you specify a precise custom interval--in this case,
    // 1 day
        alarmMgr.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis()/1000,
                AlarmManager.INTERVAL_DAY, alarmIntent);
    

    Here you need to provide the time at which you want to call the intent. In my code it is 2AM every night. Also for repeat interval I selected a day because my process needed to be called on daily basis. Ask me if you have difficulty in understanding the code or if this solve your problem mark this as accepted. Thank you.