Search code examples
androidnotificationsalarmmanager

Multiple Questions about Alarms and Notifications?


So what my goal is to make my app such that at specific times throughout the day it creates a notification for the user. For this, I am using AlarmManager to set an alarm and then when the alarm "goes off", it will create a notification. Here is how it is setup -

Class 1 - Create Alarm Class 2 - Create Notification Class 3 - Response from Notification

I have made these 3 classes because of using "intent" in creating the alarm and notification.

Here is my code -

cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 30);
    calintent = new Intent(this, NotificationMaker.class);
    calpendingintent = PendingIntent.getActivity(this, 12345, calintent, PendingIntent.FLAG_CANCEL_CURRENT);
    am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), calpendingintent);

And it calls upon the NotificationMaker class where -

    notifintent= new Intent(this, NotificationReceiver.class);
    notifpendingintent = PendingIntent.getActivity(this, 0, notifintent, 0);

    notif = new Notification.Builder(this)
        .setContentTitle("Time To Smoke!")
        .setContentIntent(notifpendingintent)
        .addAction(R.drawable.background_teal, "Open App", notifpendingintent)
        .addAction(R.drawable.background_red, "I smoked", notifpendingintent).build();
    notifm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    notif.flags |= Notification.PRIORITY_MAX;
    notif.flags |= Notification.FLAG_NO_CLEAR;
    notif.flags |= Notification.FLAG_AUTO_CANCEL;

    notifm.notify(0, notif);

the notification is being made. I have a few questions regarding this:

1) Can I perform the two tasks I want to do without using multiple classes? If so, how? (Make alarm and notification in the same class). 2) Whenever the alarm goes off, a blank layout opens and then the notification is made. How do I not have the blank page open? 3) Is there any more efficient way to perform the two tasks (make alarm to create timed notification).

Thanks in Advance!


Solution

  • As far as I can see you are using an Activity to create the Notification - better would be to use a BroadcastReciever and start a broadcast with your pending intent with AlarmManager.

    See here for more details on BroadcastReceiver