Flutter repeated weekly notification - android

Actually i want to show weekly notification in flutter, i don't find a way to i'm asking here :-)
So in my app user can schedule timetable and got notification according to that.
And user can schedule notifcation for all 7 days of week(monday, tuesday ... sunday),
now i want to repeat these notification on weekly basis, so if user scheduled notification for monday so that notification will repeat on monday, and if it is scheduled for tuesday it will repeat on tuesday and so on.
static Future showWeeklyNotification({
required int id,
String? title,
String? body,
String? payload,
required int weekday,
required Time scheduleTime,
}) async => _notifications.zonedSchedule(
id,
title,
body,
_scheduleWeekly(scheduleTime , weekday, ),
await _notificationDetails(),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.dayOfWeekAndTime,
);
static tz.TZDateTime _scheduleDaily(Time time){
final now = tz.TZDateTime.now(tz.local);
final scheduleDate = tz.TZDateTime(tz.local, now.year, now.month, now.day, time.hour, time.minute, time.second);
return scheduleDate.isBefore(now) ? scheduleDate.add(Duration(days: 1)) : scheduleDate;
}
static tz.TZDateTime _scheduleWeekly(Time time, weekDay){
tz.TZDateTime scheduleDate = _scheduleDaily(time);
print("hour");
print(time.hour);
print(time.minute);
print("weekday");
print(weekDay);
while(scheduleDate.weekday != weekDay){
scheduleDate = scheduleDate.add(const Duration(days: 1));
}
return scheduleDate;
}
I am using this code but it's not working, can anyone help me to find out what's wrong.
If i schedule it for today then it will work, but if i schedule it for next day or previous day
it seems to not work.
Thankyou in advance.

Related

Flutter yearly local notifications

I want to develop a birthday app and it should send a notification every year per person.
I am already using the 'flutter_local_notifications' package and it got the feature to periodically show a notification, but not yearly. At the moment I am just determine the next birthday of each person and everytime a user opens the app, the notifications are scheduled. But if somebody doesn't open up the app in a year, he won't be notificated.
Have anyone a solution for this?
Here is a workaround if you want to implement yearly notifications with 'flutter_local_notifications' package:
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
List<tz.TZDateTime> scheduledDateTimes = [];
int numberOfYears = 7; // Define how many years you want this notification to show
int notificationID = Random().nextInt(1000000);
DateTime startDate = DateTime.now(); // Define the starting date of this yearly notification
for (int i = 0; i < numberOfYears; i++) {
scheduledDateTimes.add(tz.TZDateTime(tz.local, date.year + i, date.month,
date.day);
}
scheduledDateTimes.asMap().forEach((index, dateTime) async {
await flutterLocalNotificationsPlugin.zonedSchedule(
int.parse("$notificationID$index"),
title,
'Notification title',
dateTime,
notificationDetails,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime);
});
Also, please take into consideration that number of local notifications you can schedule is limited to 50 for android, and 64 for iOS.

How to check freeTrialPeriod Expire Date InApp purchase in flutter

Implement InApp purchase(non-consumable) in flutter using flutter_inapp_purchase .
I have three plan 1 month, 6 month and 1 year, now i am checking is if 1 month plan then check transactionData and add 30 day to check expire date same for other 2 plan,
but problem is when user is on trial period then how can i check trial period expire date
List<String> storeItems = ['onemonth', 'sixmonth', 'oneyear'];
List<IAPItem> subscriptions = [];
List<PurchasedItem> purchasesSubscriptions = [];
StreamSubscription _purchaseUpdatedSubscription;
StreamSubscription _purchaseErrorSubscription;
StreamSubscription _conectionSubscription;
initPurchaseState(SportsProvider sportsProvider) async {
print("initPurchaseState");
await FlutterInappPurchase.instance.initConnection;
if (!mounted) return;
_conectionSubscription =
FlutterInappPurchase.connectionUpdated.listen((connected) {
print('connected: $connected');
});
_purchaseUpdatedSubscription =
FlutterInappPurchase.purchaseUpdated.listen((productItem) {
var data = jsonDecode(productItem.transactionReceipt);
int purchaseState = data["purchaseState"];
String productId = data["productId"];
String purchaseToken = data["purchaseToken"];
print("Data : ${data.toString()}, ${purchaseState}, ${productId}, ${purchaseToken}");
print('purchase-updated: $productItem');
FlutterInappPurchase.instance.finishTransaction(productItem);
});
_purchaseErrorSubscription =
FlutterInappPurchase.purchaseError.listen((purchaseError) {
print('purchase-error: $purchaseError');
});
subscriptions =
await FlutterInappPurchase.instance.getSubscriptions(storeItems);
//print("subscriptions: ${subscriptions}");
//subscriptions.forEach((f){print("subscription : ${f.freeTrialPeriodAndroid}");});
subscriptions.forEach((f){print("subscriptionPeriodAndroid : ${f.subscriptionPeriodAndroid}");});
subscriptions.forEach((f){print("subscriptionPeriodAndroid : ${f.toString()}");});
subscriptions.forEach((f){print("subscriptionPeriodAndroid : ${f.originalJson}");});
//Here we check for 1 month subscription is available or not by passig productId and days
var isSubscribedForMonth = await FlutterInappPurchase.instance.checkSubscribed(sku:subscriptions[0].productId,duration: Duration(days: 30));
print(isSubscribedForMonth);
//Here we check for 1 month subscription is available or not by passig productId and days
var isSubscribedForSixMonth = await FlutterInappPurchase.instance.checkSubscribed(sku:subscriptions[1].productId,duration: Duration(days: 180));
print(isSubscribedForSixMonth);
//Same for one year
//But how can identify the current subscription is on trial period?
// code for already subscribed
}
Have any way to identify the the current period is trial or regular.
I have tried so may solution but not get any relevant solution for my question,
please help me for the problem
if any more clarification required then just comment

FCM in android notification payload , event_time

i want to make the notification push on like maybe 5 minute after i run this http function. delete the event_time from the jsaon of notification i will receive the push notification that have timeline now, but if i hard code the event_time the time will show 50 year ago since epoch time , event i put 999 for the year it just increase by 2 year . i dint get it at all. then found Timestapm format in google and firebase so use it and the android got error whil parsing the json payload said cant fine field something . have any idea to format the Zulu RC399 time format?
pp.get('/sendCloudMessageReminderActivation', async (req, res) => {
const x = req.query.userUID;
const xstr = String(x);
const zxcv = admin.firestore().collection('user').doc(xstr);
const xoxo = await zxcv.get();
var today = new Date();
// today.setHours(today.getHours()+1);
today.setHours(today.getHours()+8);
// today.setFullYear(today.getFullYear()+50);
var xoxocode;
console.log(today+'saya saya sebelum cagbge');
// today = ISODateString(today);
const timestamp = admin.firestore.Timestamp.fromDate(today);
console.log(timestamp.nanoseconds +'siniiiiiiiiiiiiiiiiiiiii');
if (xoxo!==null) {
xoxocode= await xoxo.data().cloudMessagingToken;
const message = {
notification: {
title: 'your account is still in active state',
body: 'Tap here to check it out!'
},
android:{
priority:'high',
// important : 'MAX',
notification:{
notification_priority: "PRIORITY_MAX",
event_time: timestamp,// when ever i cahnge this event use ZULU RC339 format i still give my 50 year ago notification. i did my research but cant figure out how to do this ,
default_sound: true,
// notification_priority: PRIORITY_MAX
}
},
token: xoxocode
};
// res.status(200).send('authorized');
const respondfrommesage = admin.messaging().send(message);
console.log(respondfrommesage);
res.status(200).send('message send notification');
}
res.end();
});
Zulu is not a time format. It's a time zone. Zulu is just another name for UTC.
As per this article:
Another name for UTC Time is "Zulu" or "Z Time."
Now, about the timestamp value. If you are creating a Date object and use milliseconds or nanoseconds property of a date, it will always give you the difference in respective property type (mills/nano),
From the time you created the instance and starting time of UNIX which is 1 January 1970.
It has been 50 years as of 1st Jan, 2020. Hence the 50 year difference in the event_time.
If you have any other doubts let me know.

Notifications are never shown in emulator

I am trying to show a notification at a certain date and time. I have tried a lot, but it is never showing in the emulator. I found and edited this piece of code:
createnotification() {
let remindid = new Date().getUTCMilliseconds();
this.date = moment(“2019-01-31 12:20:00”).format(“YYYY-MM-DD HH:mm:ss”);
let notification = {
id: remindid,
title: this.title,
text: this.description,
forceShow: 'true',
coldstart: true,
foreground: false,
at: this.date
};
cordova.plugins.notification.local.schedule(notification);
let alert = this.alrtCtrl.create({
title: 'Notifications set at ' + this.date,
buttons: ['Ok']
});
alert.present();
}
I think it has something to do with the “at” property. I tried different variations of the date, used the “trigger”-property. Nothing seems to work.
What am I missing?
Fixed:
Monthnumbers are zero based, so I was pointing at March.
January = 0
February = 1
March = 2
Etc.

Phonegap: local notification repeat every Sunday of the week?

I'm trying to implement the Phonegap local notification in my project.
I'm using this plugin:
de.appplant.cordova.plugin.local-notification-custom
I have installed the plugin and tested it and it works fine.
I tested it with this code and it works fine:
cordova.plugins.notification.local.schedule({
id : 1,
title : 'I will bother you every minute',
text : '.. until you cancel all notifications',
sound : null,
every : 'minute',
autoClear : false,
at : new Date(new Date().getTime() + 10*1000)
});
The above notification will run every minute and work fine.
Now, I need to set a local notification that will only run on every Sunday and every week.
I came across something like this but when tested it, it does nothing:
cordova.plugins.notification.local.schedule({
id: 1,
title: "Test...",
text: "Test...",
sound: null,
every: 'week',
at: sunday_16_pm
});
I don't even know if at: sunday_16_pm is correct or not!
Could someone please advice on this issue?
Thanks in advance.
EDIT:
After searching for hours and finding nothing, I just came across this documentation:
https://github.com/katzer/cordova-plugin-local-notifications/wiki/04.-Scheduling
They have a sample code that says:
Schedule Repeatedly
cordova.plugins.notification.local.schedule({
text: "Delayed Notification",
firstAt: monday,
every: "day",
icon: "file://img/logo.png"
}, callback);
But what is monday?!? is that a variable? And if so, how do you create that variable?
I don't understand why people write documentation as if no one else would want to read/understand them!!
Another edit:
I found this which explains exactly what i'm trying to do but I'm not using ionic and never have. So I don't understand the code that is provided there at all!
https://www.joshmorony.com/getting-familiar-with-local-notifications-in-ionic-2/
I don't know about those variables sunday_16_pm or monday either, but you can use your own variable with firstAt.
First of all you have to find the timestamp for sunday_16_pm to tell this plugin that the repeating should start on sunday afternoon.
In order to find this timestamp (that I suppose this should be done dynamically), I wrote the function getDayMillDiff to calculate the time-difference between now and sunday. Afterwards this difference is used to obtain the desired sunday_16_pm.
function getDayMillDiff(refday){
var days = {
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
sunday: 0
};
if(!days.hasOwnProperty(refday))throw new Error(refday+" is not listed in "+JSON.stringify(days));
var curr = new Date();
var triggerDay = days[refday];
var dayMillDiff=0;
var dayInMill = 1000*60*60*24;
// add a day as long as refday(sunday for instance) is not reached
while(curr.getDay()!=triggerDay){
dayMillDiff += dayInMill;
curr = new Date(curr.getTime()+dayInMill);
}
return dayMillDiff;
}
var today = new Date();
// how many days are between current day (thursday for instance) to sunday, add this difference to this sunday variable
var sunday = today.getTime() + getDayMillDiff("sunday");
// convert timestamp to Date so that hours can be adjusted
var sunday_16_pm = new Date(sunday);
sunday_16_pm.setHours(16,0,0);
// now we can use sunday_16_pm to schedule a notification showing at this date and every past week
cordova.plugins.notification.local.schedule({
id: 1,
title: "Test...",
text: "Test...",
every: 'week',
firstAt: sunday_16_pm
});
One more example:
To test getDayMillDiff for other days than sunday, you can simply pass the string "monday" onto it (please use always a name listed within the variable days in getDayMillDiff):
var today = new Date();
var monday = today.getTime() + getDayMillDiff("monday");
var monday_10_am = new Date(monday);
monday_10_am.setHours(10,0,0);
cordova.plugins.notification.local.schedule({
id: 1,
title: "Test...",
text: "Test...",
every: 'week',
firstAt: monday_10_am
});
Hope it helps.

Categories

Resources