0

so I'm having this problem that whenever I set an Alarm it just sends the notification even though the time doesn't match. I'm using this class to set the alarm and cancel the alarm.

package com.example.home.quoteapp.notification;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import com.example.home.quoteapp.readers.NotificationsReader;

import java.util.Calendar;

public class AlarmActivater {
private final Context context;

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

public void setAlarm() {
    cancelAlarm();
    if (!NotificationsReader.getNotifications().isEmpty()) {
        SharedPreferences prefs = context.getSharedPreferences("time", Context.MODE_PRIVATE);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, prefs.getInt("hour", 1));
        calendar.set(Calendar.MINUTE, prefs.getInt("minute", 01));
        calendar.set(Calendar.SECOND, 0);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }
}

private boolean isActive() {
    return (PendingIntent.getBroadcast(context, 0,
            new Intent(context, AlarmReceiver.class),
            PendingIntent.FLAG_NO_CREATE) != null);
}

private void cancelAlarm() {
    if (!NotificationsReader.getNotifications().isEmpty() && isActive()) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent myIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                context, 0, myIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.cancel(pendingIntent);
    }
}
}

I call the setAlarm method on startup of the app and when changing the time in a time picker. The prefs.getInt... stuff is correct I have tested that.

Kiraged
  • 519
  • 2
  • 9
  • 28
  • the alarm will be fired immediately if the time is expired, you can check whether `calendar.getTimeInMillis()` is smaller than current time. – mike Apr 15 '18 at 15:44
  • You're right, how would I make it so that if it's smaller than current time that it would activate on the correct time? – Kiraged Apr 15 '18 at 16:04
  • After you set the values on your alarm `Calendar`, compare it to the current time, and add a day if it's in the past. `Calendar.getInstance()` returns an instance set to the current date/time, so just compare yours against that, like is shown in answer on the linked duplicate. – Mike M. Apr 15 '18 at 19:35

0 Answers0