Search code examples
androidandroid-servicealarmmanagerandroid-pendingintent

How to schedule at particular time service in android


I am making demo android project in which I want to schedule service daily at 8:00 clock. I am calling this method from my launcher activity. Whenever I start application then below method is called then at the same time it start service and display notification. I only want it should schedule in such a way it should execute at 8:00 instead of everytime I open app.

public static void scheduleVerseNotificationService(Context mContext) {
    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(mContext, Notification.class);
    PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, intent, 0);

    // Set the alarm to start at approximately 08:00 morning.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 8);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

}

Thanks


Solution

  • It seems you schedule timer for time which is already passed so it is called as soon you request alarmManager.setInexactRepeating

    Here is code to fix your issue:

    public static void scheduleVerseNotificationService(Context mContext) {
        AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(mContext, Notification.class);
        PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, intent, 0);
    
        // reset previous pending intent
        alarmManager.cancel(pendingIntent);
    
        // Set the alarm to start at approximately 08:00 morning.
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
    
        // if the scheduler date is passed, move scheduler time to tomorrow
        if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }
    
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, pendingIntent);
    }