I tried implemented it UNCalendarNotificationTrigger and then tried to schedule next day's notification in WillPresentNotification. It worked until the application was in foreground but as soon as it went background it stopped scheduling for next day.
I tried using UNTimeIntervalNotificationTrigger but the problem is that it will display same notification daily however my requirement is to display different notification daily for unlimited period until user stops it from within the application or via iOS itself.
Is there some way that I can modify the title and body of the next notification to be displayed using UNTimeIntervalNotificationTrigger?
Thanks.
Here is the sample to repeat an alarm everyday at 09:30 by using local notification in Xamarin iOS, you could have a look:
// 1
var dateComponents = new NSDateComponents();
dateComponents.Hour = 9;
dateComponents.Minute = 30;
var trigger = UNCalendarNotificationTrigger.CreateTrigger(dateComponents, true);
// 2
var content = new UNMutableNotificationContent();
content.Title = "Daily reminder";
content.Body = "Enjoy your day!";
var requestID = "request_" + id;
var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);
// 3
UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
if (err != null)
{
}
});
Related
i am trying to understand how an android app on a device could send a notification to another android app on another device when a user adds a record to sql server database or deletes one. i started my research and figured out that i must use FCM. i applied this tutorial https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=windows and it worked but it didn't help me understand how the android app well send the notification. i tried to apply codes from java like this one https://blog.heyday.xyz/send-device-to-device-push-notifications-without-server-side-code-238611c143, i tried to convert it to c# but it didn't work for me. i actually didn't know how to completely write it as c#. i also tried this one: Xamarin android FCM Notification Client to client(phone to phone) but in vain. i searched a lot but i don't know why it feels complicated. if anyone could help me find a tutorial to do so. thanks in advance.
To send notifications from one device to another in Xamarin.android there are several ways:
using firebase cloud messaging when add new row to database
Example:
//process that add new row
//post on FCM
note: receive device must be register device token in firebase cloud messaging
for more details:
https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/firebase-cloud-messaging
using task work in background in reciver device and check the number of row in database
example:
Task.Run(()=>{
//code that check number of row
});
if changed call this method :
public void SendNotification(int periority_notification, return_user_info User_info, Context context)
{
/*here intent to open layout when click on notification*/
Intent inten = new Intent(context, typeof(MainActivity));
const int pendingIntentId = 0;
PendingIntent pendingIntent =
PendingIntent.GetActivity(context, pendingIntentId, inten, PendingIntentFlags.OneShot);
var title = User_info.User_Email;
var message = User_info.User_Name.Trim() + " Reserved Request";
using (var notificationManager = NotificationManager.FromContext(context))
{
Notification notification;
if (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.O)
{
notification = new Notification.Builder(context)
.SetContentIntent(pendingIntent)
.SetContentTitle(title)
.SetContentText(message)
.SetAutoCancel(true)
.SetPriority(1)
.SetSmallIcon(Resource.Drawable.carparts)
.SetDefaults(NotificationDefaults.All)
.Build();
}
else
{
var myUrgentChannel = context.PackageName;
const string channelName = "SushiHangover Urgent";
NotificationChannel channel;
channel = notificationManager.GetNotificationChannel(myUrgentChannel);
if (channel == null)
{
channel = new NotificationChannel(myUrgentChannel, channelName, NotificationImportance.High);
channel.EnableVibration(true);
channel.EnableLights(true);
channel.LockscreenVisibility = NotificationVisibility.Public;
notificationManager.CreateNotificationChannel(channel);
}
channel?.Dispose();
notification = new Notification.Builder(context)
.SetContentIntent(pendingIntent)
.SetChannelId(myUrgentChannel)
.SetContentTitle(title)
.SetContentText(message)
.SetAutoCancel(true)
.SetSmallIcon(Resource.Drawable.carparts)
.Build();
}
notificationManager.Notify(periority_notification, notification);
notification.Dispose();
}
}
I'm developing a Xamarin.Android application that uses a Foreground Service to track user's location after certain time/distance.
To keep the service running I have an ongoing notification with Low priority as well as the notification channel with low priority too. I've tried all kind of combinations (low and min priorities and content texts).
NotificationChannel code:
private NotificationChannel CreateNotificationChannel(string channelId)
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
return null;
}
string channelName = Resources.GetString(Resource.String.notification_channel_name);
string channelDesc = Resources.GetString(Resource.String.notification_channel_desc);
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationImportance.Default)
{
Description = channelDesc
};
switch(channelId)
{
case UPDATES_NOTIFICATION_CHANNEL_ID:
notificationChannel.Importance = NotificationImportance.High;
break;
case ONGOING_NOTIFICATION_CHANNEL_ID:
notificationChannel.Importance = NotificationImportance.Low;
break;
default:
break;
}
var notifManager = (NotificationManager)GetSystemService(NotificationService);
notifManager.CreateNotificationChannel(notificationChannel);
return notificationChannel;
}
Notification code:
private Notification CreateOngoingNotification()
{
Intent notificationIntent = new Intent(this, typeof(MainActivity));
PendingIntent pendingIntent =
PendingIntent.GetActivity(this, 0, notificationIntent, 0);
string content = "The application is fetching your location every " + MIN_TIME / (60 * 1000) + " minutes if you moved at least " + MIN_DISTANCE + " meters.";
NotificationCompat.Builder builder;
if (Build.VERSION.SdkInt < BuildVersionCodes.O) builder = new NotificationCompat.Builder(this);
else builder = new NotificationCompat.Builder(this, m_ongoingNotificationChannel.Id);
builder
.SetContentTitle("Persistent notification")
.SetStyle(new NotificationCompat.BigTextStyle().BigText(content))
.SetSmallIcon(Resource.Drawable.ic_notification)
.SetContentIntent(pendingIntent)
.SetGroup("persistent")
.SetOngoing(true)
.SetVisibility((int)NotificationVisibility.Private)
.SetPriority((int)NotificationPriority.Low);
Notification notification = builder.Build();
return notification;
}
Having the following image in mind, what I'm trying to acomplish is the style of the notifications from LinkedIn app, the Google Weather one (bottom), and the other one (3rd one starting from the end).
All I can get is the one with "Persistent notification" in the title.
Any kind of help will be welcome!
EDIT: made clear that I'm using Xamarin, not Java
If I am not wrong and you are looking for an expandable notification
A basic notification usually includes a title, a line of text, and one or more actions the user can perform in response. To provide even more information, you can also create large, expandable notifications by applying one of several notification templates.
Now if you read the documents carefully it has all the different types of expandable notifications,
The one you are looking for is either the Add a large block of text or the Create an inbox-style notification
Both codes available on the documentation are easily convertible to C# i.e. Xamarin.Android
In case you face issues or have queries feel free to revert
Goodluck
I am working on an ASP.NET Webform project (legacy code).On my button_click event i am sending sms message to all the datas populated in this.
var customerSMS = BusinessLayer.SMS.SmsSetup.GetAllCustomerSMS(OfficeId);
This takes around 15seconds to do all the computing and get the data(1000rows)
from the Db.And for each data it runs through the loop and does validation and
sends the sms and it does take time.I want to do this task in background and
redirect the user to the index page and the background process continues till it
gets out of the loop.I am new to this and still learning this beautiful
language C#.I did go through this amazing Asynchronous Programming async/await
and Multithreading approach and got hold of it only in simple WindowsForm
applications.Any reference/code snippet/best approach with a simple explanation for my case would be helpful.
My button click event code :
protected void ReturntoDashboard_Click(object sender, EventArgs e)
{
sms = Everest.Net.BusinessLayer.SMS.SmsSetup.GetSmsSetUp(OfficeId);
if (sms.EnableSmsData && sms.SmsCount > 0)
{
#region Loan Section
var smsLoan = Everest.Net.BusinessLayer.SMS.SmsSetup.GetLoanId(s.Sms_AccountNumber);
var loanId =
BusinessLayer.SMS.SmsSetup.GetLoanIdValue(s.Sms_AccountNumber);
var dateexceeded =
BusinessLayer.SMS.SmsSetup.IsDateExceeded(loanId);
if (smsLoan != null && dateexceeded == true)
{
foreach (Common.SMS.SMSSetup sm in smsLoan)
{
var smsClosingBalanceLoan = BusinessLayer.SMS.SmsSetup.GetAmountForLoanAlert( sm.LoanId,
BusinessLayer.Core.DateConversion
.GetCurrentServerDate()
.AddDays(sms.DaysbeforeLoanalerts).ToString());
if (smsClosingBalanceLoan != null)
{
if (smsClosingBalanceLoan.LoanAmountToPay > 0)
{
int smsSentAlertCount = sms.LoanAlertCount;
var logCount = BusinessLayer.SMS.SmsSetup.GetLoanSmsAlertSentCount(DateTime.Now.AddDays(-smsSentAlertCount).ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"), sm.LoanAccountNumber);
if (logCount < smsSentAlertCount)
{
smsLog = new Everest.Net.Common.SMS.SMSSetup();
finalMessage = "Dear Member, Your Loan accnt " + sm.LoanAccountNumber + " with Principal"+ "+" + "Int Amnt: Rs." + smsClosingBalanceLoan.LoanAmountToPay + " need to be payed.Thank You," + officeName.OfficeName;
smsLog.LogServiceType = "Loan";
smsLog.LogSmsType = s.Sms_SmsType;
smsLog.LogSmsMessage = finalMessage;
smsLog.LogCustomerId = s.CustomerId.ToString();
smsLog.LogAccountNumber = s.Sms_AccountNumber;
smsLog.LogAccountType = s.Sms_AccountType;
smsLog.LogSmsSentDate = BusinessLayer.Core.DateConversion.GetCurrentServerDate();
smsLog.LogSmsFailedDate = "";
smsLog.LogSentStatus = true;
smsLog.LogUserId = UserId;
smsLog.LogSmsFailedMessage = "";
try
{
var result = Everest.Net.BusinessLayer.SMS.smsParameters.SendSMS(sms.FromNum, sms.Token, sms.Url, cellNum, finalMessage);
}
catch (Exception ex)
{
smsLog.LogSmsFailedDate = System.DateTime.Now.ToString("MM/dd/yyyy HHmmss");
smsLog.LogSentStatus = false;
smsLog.LogSmsFailedMessage = ex.Message;
Everest.Net.BusinessLayer.SMS.SmsSetup.InsertSMSLog(smsLog);
}
sms = Everest.Net.BusinessLayer.SMS.SmsSetup.GetSmsSetUp(OfficeId);
sms.SmsCount = sms.SmsCount - 1;
Everest.Net.BusinessLayer.SMS.SmsSetup.UpdateSmsSetup(sms);
Everest.Net.BusinessLayer.SMS.SmsSetup.InsertSMSLog(smsLog);
}
}
}
}
}
}
}
}
catch (Exception ex)
The ideal solution would remove the responsibility of sending the SMS from the web application itself. Instead, the web application should create a database record containing the message and recipient addresses, and a separate background job (e.g. a Windows Service) should poll the database and send SMS messages when neeeded. This is the best solution in terms of fault tolerance and auditability, because there is a permanent record of the messaging job which can be resumed if the system fails.
That being said, maybe you don't want to go to all that trouble. If you feel strongly that you wish to send the SMS directly from the ASP.NET application, you will need to create a Task and queue it to run using QueueBackgroundWorkitem. You will need to refactor your code a bit.
Move all the logic for sending the SMS into a separate function that accepts all the information needed as parameters. For example,
static void SendSMS(string[] addresses, string messagetext)
{
//Put your SMS code here
}
When you need to call the function, queue it as a background item
HostingEnvironment.QueueBackgroundWorkItem(a => SendSMS(addresses, messageText));
If your worker task needs to access its own cancellation token (e.g. if it is supposed to loop until cancelled), it is passed as an argument to the lambda expression. So you could modify the prototype
static void SendSMS(string[] addresses, string messagetext, CancellationToken token)
{
while (!token.IsCancellationRequested)
{
//Put your code here
}
}
and pass it thus:
HostingEnvironment.QueueBackgroundWorkItem(token => SendSMS(addresses, messageText, token));
Placing the task in the background queue ensures that ASP.NET keeps track of the thread, doesn't try to garbage collect it, and shuts it down properly when the application pool needs to shut down.
After queuing the background operation, your page can render is content per usual and conclude the HTTP response while the task continues to execute.
I've been trying to implement a BackgroundTask for Raw Push Notifications on my Windows and Windows Phone 8.1 apps but it doesn't seem to be working. I've successfully managed to get toast based push notifications working but as far as I'm aware a Raw notification silently pushes data to the app and it's up to the app to display a toast notification or update the app's tile.
I've looked at the BackgroundTask Sample and followed it exactly yet nothing works (https://code.msdn.microsoft.com/windowsapps/Background-Task-Sample-9209ade9).
Here's the steps I've taken
Created a Windows Runtime Component Project in the same solution as my other projects (Called NotificationServer)
Renamed the class to RawTask.cs and implemented IBackgroundTask and its Run method
Created a method to create a toast notification
private void SendNotification(string text)
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
XmlNodeList elements = toastXml.GetElementsByTagName("text");
foreach (IXmlNode node in elements)
{
node.InnerText = text;
}
ToastNotification notification = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(notification);
}
Added code to the Run method
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
string content = notification.Content;
// ...
SendNotification("test");
// ...
_deferral.Complete();
Updated my App's manifest to Toast Capable = YES and Lock Screen Notifications = Badge
Added a Declaration for a Background Task with Supported Task Type = Push Notification and Entry Point = NotificationServer.RawTask
Added code to register the Background Task
public static BackgroundTaskRegistration RegisterBackgroundTask(string taskEntryPoint,
string taskName,
IBackgroundTrigger trigger,
IBackgroundCondition condition)
{
//
// Check for existing registrations of this background task.
//
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == taskName)
{
//
// The task is already registered.
//
return (BackgroundTaskRegistration)(cur.Value);
}
}
//
// Register the background task.
//
var builder = new BackgroundTaskBuilder();
builder.Name = taskName;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
if (condition != null)
{
builder.AddCondition(condition);
}
BackgroundTaskRegistration task = builder.Register();
return task;
}
And executing it with
var reg = RegisterBackgroundTask("NotificationServer.RawTask", "RawNotifications", new PushNotificationTrigger(), null);
Is there something I'm missing here, my app doesn't seem to be responding to the Push Notification event. I have made sure my app is associated with the app in the store and the pushes are being sent with the correct client secret and app ID.
There are four types of push notifications:
Tile update
Badge update
Toast notification
Raw notification
All Windows Runtime apps can use the first three push notifications when in the foreground. Only lock screen apps can receive raw push notifications from WNS.
so, you must make your app a lock screen app.
You can follow this topic to do that.
I have an app which can(possibly) show two toast notifications to the user one after the other. I observed that if such scenario arises then only one of the two notifications is displayed to the user but once the user launches the app and then same notifications are presented to the user in message boxes and if he clicks "cancel" for the first message and then the next notification is presented. So, my doubt now is, If two toast notifications are there then how will the device handle it? and which of the two is displayed to the user? And in case only notification is presented to the user (by default behaviour of the device) then is there a way to display notifications one after the other?
This is similar to this QUESTION but i want to know the behaviour of WP7 phones as the features of WP7 very different other smartphone OSes.
All suggestions, comments and answers are appreciated.
Thank You
Windows Phone 7 has the potential to show both the messages, and which one first depends on which one the phone receives first.
If you look at the diagram on this page http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402558(v=vs.92).aspx you see that there is a lot of communication in sending a push (toast, tile or raw) notification. And it depends on the Microsoft Push Notification Service which normally sends it first come first serve.
So from the sounds of it, I would look into trying to limit how your application sends the toast notifications. So check if a toast notification has been sent to the phone within a certain amount of time, if so hold of on sending the next one in till that time has past.
Also remember to check if the MPNS actually sent the push notification to the, that will help in determining if the phone might have received the notification
In that link I post it goes into a lot of details about sending and receiving the push notifications.
What I did is this,
public static void ShowToast()
{
try
{
string langKey = CacheManager.getInstance().getDataFromConfigFile(CacheManager.APP_CURRENT_LANGUAGE);
string flag = CacheManager.getInstance().getDataFromConfigFile(CacheManager.APP_UPGRADE_STATUS);
string catalogUpdateFlag = CacheManager.getInstance().getDataFromConfigFile(CacheManager.APP_CATALOG_UPGRADE_STATUS);
CultureInfo ci;
if ((null == langKey) || (langKey.Equals(Utils.LANGUAGE_EN)))
{
ci = new CultureInfo("en-US");
}
else
{
ci = new CultureInfo("fr-FR");
}
AppResources.Culture = ci;
if (!Utils.isNullString(flag))
{
var toast = new ShellToast
{
Title = AppResources.APP_NAME,
Content = getMessageStatus(flag),
NavigationUri = new System.Uri("/MainPage.xaml", System.UriKind.Relative)
};
Logger.log(TAG, ":ShowToast():MessageToUser" + AppResources.APP_NAME + getMessageStatus(flag));
toast.Show();
}
if (!Utils.isNullString(catalogUpdateFlag))
{
var toast = new ShellToast
{
Title = AppResources.APP_NAME,
Content = getMessageStatus(catalogUpdateFlag),
NavigationUri = new System.Uri("/MainPage.xaml", System.UriKind.Relative)
};
Logger.log(TAG, ":ShowToast():MessageToUser" + AppResources.APP_NAME + getMessageStatus(catalogUpdateFlag));
toast.Show();
}
}
catch (Exception ex)
{
Logger.log(TAG, "Exception in ShowToast: " + ex.Message + "\n" + ex.StackTrace);
}
}
private static string getMessageStatus(string flagType)
{
//string flag = CacheManager.getInstance().getApplicationSettings(CacheManager.APP_UPGRADE_STATUS);
string flag = CacheManager.getInstance().getDataFromConfigFile(CacheManager.APP_UPGRADE_STATUS);
string catalogUpdateFlag = CacheManager.getInstance().getDataFromConfigFile(CacheManager.APP_CATALOG_UPGRADE_STATUS);
if (flagType == flag)
{
if (flag.Equals(CacheManager.MAJOR_UPGRADE))
{
return AppResources.APP_UPGRADE_CONFIRM;
}
else if (flag.Equals(CacheManager.MINOR_UPGRADE))
{
return AppResources.APP_UPGRADE_MINOR_CONFIRM;
}
}
else if (flagType == catalogUpdateFlag)
{
return AppResources.APP_CATALOG_CONFIRM;
}
return "";
}
I have taken two different variables to know if its the application upgrade or just the catalogue upgrade(New items will be added to the existing ones). So if there is catalogue upgrade and/or application upgrade user will be notified.