How to Set Local Notifications Between 8Am and 8Pm Every Day

how to set local notifications between 8am and 8pm every day

Unfortunately you do need to add a notification request for each 30 minute interval in the 8am-8pm window. What is your aversion to this approach? It's a simple for-loop. Instead of using a UNTimeIntervalNotificationTrigger you would use a UNCalendarNotificationTrigger.

let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removeAllDeliveredNotifications()
notificationCenter.removeAllPendingNotificationRequests()

let startHour = 8
let totalHours = 12
let totalHalfHours = totalHours * 2

for i in 0...totalHalfHours {
var date = DateComponents()
date.hour = startHour + i / 2
date.minute = 30 * (i % 2)
print("\(date.hour!):\(date.minute!)")

let notification = UNMutableNotificationContent()
notification.title = "You should have some water"
notification.body = "It has been a long time since you had some water, why don't you have some."
notification.categoryIdentifier = "reminder"
notification.sound = .default

let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: notification, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: nil)
}

Local Notification only during given time period

When you set notification fire time, just make a check if current time is more than 8am and less than 8pm. Else, if notification fire time is not inside this interval, change fire time to next day. Simple as that.

i want show notification at 8:00 am everyday

alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(context of current file, AlarmReceiver1.class);

pendingIntent = PendingIntent.getBroadcast(Menu.this, 0, alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT);
alarmIntent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
alarmManager.cancel(pendingIntent);

Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 8);
alarmStartTime.set(Calendar.MINUTE, 00);
alarmStartTime.set(Calendar.SECOND, 0);
if (now.after(alarmStartTime)) {
Log.d("Hey","Added a day");
alarmStartTime.add(Calendar.DATE, 1);
}

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("Alarm","Alarms set for everyday 8 am.");

Coming to the broadcast receiver class. You need to register your broadcast receiver in the manifest. This will cause you to receive clock events.
Override the onReceive method of this broadcast receiver and make a notification there itself or make a seperate notification building service and build and display your notification there.

The manifest code snippet:

<receiver android:name="AlarmReceiver1"  android:enabled="true">

The broadcast receiver code snippet:

public class AlarmReceiver1 extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, NotificationService1.class);
service1.setData((Uri.parse("custom://"+System.currentTimeMillis())));
context.startService(service1);
}

Notification building service code snippet:

public class NotificationService1 extends IntentService{

private NotificationManager notificationManager;
private PendingIntent pendingIntent;
private static int NOTIFICATION_ID = 1;
Notification notification;
@Override
protected void onHandleIntent(Intent intent) {
ontext context = this.getApplicationContext();
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this, Activity to be opened after clicking on the notif);
Bundle bundle = new Bundle();
bundle.putString("test", "test");
mIntent.putExtras(bundle);
pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Resources res = this.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
notification = new NotificationCompat.Builder(this)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
.setTicker("ticker value")
.setAutoCancel(true)
.setPriority(8)
.setSound(soundUri)
.setContentTitle("Notif title")
.setContentText("Text").build();
notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
notification.ledARGB = 0xFFFFA500;
notification.ledOnMS = 800;
notification.ledOffMS = 1000;
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
Log.i("notif","Notifications sent.");

}

}

How do I set up local user notifications that are set off by certain dates

Create an extension that will create date components from your data:

extension Int {

var month: Int {
return self / 100
}

var day: Int {
return self % 100
}
}

Create notification triggers based on date components:

let date = allDiscounts.list[myList[0]].dateApplied

let components = DateComponents(month: date.month,
day: date.day,
hour: 10, minute: 00, second: 00)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)

let identifier = "\(date)"
let content = UNNotificationContent(
let request = UNNotificationRequest(identifier: identifier,
content: content,
trigger: trigger)


Related Topics



Leave a reply



Submit