[FIXED] Alarm manager not triggering

Issue

I’m new to this, so I’m a bit lost.

I have built a notification and passed it to the alarm manager as a pendingIntent, however instead of waiting the interval to trigger the alarm and showing the notification, the notification is instantly shown.
What have I done wrong, that isn’t allowing the alarm to be set properly?

public class NotificationController{

Context context;

public void createNotification(Context context){

    this.context = context;
    Notification notification = getNotification();

    //creates notification
    Intent intent = new Intent(context, NotificationReceiver.class);
    intent.putExtra(NotificationReceiver.NOTIFICATION_ID, 1);
    intent.putExtra(NotificationReceiver.NOTIFICATION, notification);
    PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    //schedules notification to be fired.
    AlarmManager  alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 10000 , pIntent);

}


private Notification getNotification(){

    Intent intent = new Intent(context, MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);

    Notification.Builder builder = new Notification.Builder(context)
            .setContentTitle("Reminder")
            .setContentText("Car service due in 2 weeks")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent);
    return builder.build();
}
}

my receiver

public class NotificationReceiver extends BroadcastReceiver {

public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";

public void onReceive(Context context, Intent intent) {

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = intent.getParcelableExtra(NOTIFICATION);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(id, notification);

}
}

I have also registered with <receiver android:name=".NotificationReceiver" > in the AndroidManifest.

Solution

In this line

alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 10000 , pIntent);

You specify that the alarm has to fire at 10 seconds after the device has been booted (which is in the past, so the alarm fires immediately). If you would want it 10 seconds after you set the alarm, you use the number of milliseconds since the device has been booted PLUS 10 seconds:

alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis() + 10000 , pIntent);

Answered By – MarchingHome

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published