androidalarmmanagerrepeatingalarm

Alarm Triggered Immediately when I set AlarmManager what Im doing wrong in below code


Alaram Manager Class

Im using alaramManager.setRepeating for repeating every time after some Interval

public class AlarmService {

Long time;
AlarmManager alarmManager;
PendingIntent pendingIntent;
Context context;

public AlarmService(Context context){
    this.context = context;
}

public AlarmService(Context context, Long time) {
    this.time = time * 60000;
    Log.e("time",this.time+" AlaramService");
    this.context = context;
}

public void setAlarm() {
    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, ReminderBroadcastReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), time, pendingIntent);

    Log.e("time",time+" setAlarm");

}

public void cancelAlarm() {
    Intent intent = new Intent(context, ReminderBroadcastReceiver.class);
    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent,0);
    alarmManager.cancel(sender);
}

}

setting AlarmManager to call after specific time

Long time = Long.valueOf(settingsData.getInterval().split(" ")[0]);
                AlarmService alarmService = new AlarmService(Setting.this,time);
                alarmService.cancelAlarm();
                alarmService.setAlarm();

ReminderBroadcastService for Notification

public class ReminderBroadcastReceiver extends BroadcastReceiver {


@Override
public void onReceive(final Context context, Intent intent) {
    Toast.makeText(context, "Received", Toast.LENGTH_SHORT).show();

    NotificationService notificationService = new NotificationService(context);
    notificationService.callNotification();
}

Solution

  • You are passing System.currentTimeMillis()

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), time, pendingIntent);
    

    for alarm time in set alarm function. That's why it triggering immediately. Pass the future time instead like setting alarm next day at same time as now

    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+86400000L, time, pendingIntent);