UWP scheduled Notification, Toast after app is closed - c#

now, I'm developing some notification app about the online contest.
image:
I managed to get HttpResponse, and parse it to my Class, and add my app as a startup program.
the problem is that I can't find a good way to How notify my app user.
yesterday, I founded Appointment class and I used it. but always, Appointment should be accepted by user's hand. and It is quite slow, and sometime it crashed.
while (mys.Count != 0)
{
Contest contest = mys.Pop();
var appointment = new Appointment();
appointment.Location = "Codeforces";
appointment.Subject = contest.name;
appointment.StartTime = contest.startDate;
appointment.Reminder = TimeSpan.FromHours(1);
var rect = new Rect();
string tmp = await AppointmentManager.ShowAddAppointmentAsync(appointment, rect);
list.Add(contest); //<- observable collection
}
so I changed my mind to use toast notification class. because I think it doesn't need to be accepted by user.
the main question is"
I wonder how can i push notification about the events which will be held in several days.
I mean
my App user just once execute my App.
my App Queried to website, and get some event. (I did {1, 2})
for all appropriate event, I want to push all event to Toast Notification that is valid after my App is closed or my Computer re-boot.
I downloaded Karaoke one App from MS Store, and it pushes Notification periodically 24 hours, even it has no background process(I think), and even I never execute app after rebooting.
below image is Karaoke one App Notification.
How can i Implement it?.
Thanks for read.

Related

OneSignal Chrome multiple notification

I have some problem with web push notification.
I'm able to send the notification regularly, but, when I send two notification and the first is still visible on the screen, the second overwrite the first one.
The REST API is called by an MVC site written with C#, the object I send is the following:
var obj = new
{
app_id = _appKey,
contents = new { en = message },
headings = new { en = title },
included_segments = new[] { "All" },
url,
chrome_web_icon = imageUrl,
priority = 1,
id = DateTime.Now.ToString("yyyyMMddHHmmss")
};
Did anyone experienced the same issue?
How can I solve that?
Got this answer from OneSignal person.
When using our REST API to programmatically send notifications, you can use the undocumented parameter web_push_topic.
In a set of notifications sharing the same web_push_topic, newly received notifications will replace older received notifications with the same topic. Only notifications sharing the same topic will be replaced; notifications without a topic or with a different topic will not be replaced. You can set different topics for different sets of notifications to control which notifications stay on screen.
The web_push_topic value can be any string value.
On Chrome, a maximum of 3 notifications is displayed at any time, even if the other notifications are not related to your site or from OneSignal. This means you can only show 3 categories of notifications to your user, not counting for other notifications that might be displayed at that time.
On Firefox on Windows, many more notifications can be shown at a time (6+).
On Firefox on Mac, and Safari on Mac, only one notification can be shown at a time, even if the other notifications are not related to your site or from OneSignal. Notifications also disappear quickly within 5 seconds and this time is not customizable.
On Chrome/Firefox on Android, multiple notifications can be shown at a time.
If you do not specify web_push_topic , each notification will be replaced by a newer notification. If you do specify web_push_topic, you can choose which notifications will be replaced and which notifications will stack.
When sending a notification using our API, setting a string value for web_push_topic will set the topic for the notification. Any notifications sharing the same topic will replace each other, but any notifications with a different topic won't be replaced.
So suppose you send 4 notifications:
Notification "Open house at 1234 Street at 3 PM this Saturday" with topic 'open-houses'.
Notification "Open house at 1234 Street changed to 4 PM this Saturday" with topic 'open-houses'.
Notification "20 new houses match your criteria in the Seattle, WA" with topic 'general-updates'.
Notification "Find an agent in your area" with topic 'promotional'.
The sequence of notifications observed will be:
Notification #1 shows.
Notification #2 replaces #1 (even if docked in Mac OS X's notification tray).
Notification #3 is shown separately (and if docked in Mac OS X's notification tray, it will use a separate entry).
Notification #4 is also shown separately.
In the end, when the subscriber checks his unread notifications, he will see three total notifications.
Example Code:
payload = {"app_id": "5eb5a37e-b458-11e3-ac11-000c2940e62c",
"include_player_ids": ["6392d91a-b206-4b7b-a620-cd68e32c3a76"],
"contents": {"en": "English Message"},
"web_push_topic": 'Unique for every notification'}
OneSignal intentionally implements notification replacement that results in this behavior.
The reason for this is to avoid cases where a subscriber could end up with up to 100 notifications to dismiss from a single website, which would be a terrible experience for them.
In the future OneSignal may allow you to avoid this limitation, but in most cases we wouldn't recommend doing this differently.

How to check if Windows Universal 10 app is closed not minimised?

Hi guys I am aware that OnSuspending function in the app.xaml file allows me to save information should my app be suspended. I want my user to be automatically logged out in my database should the application be closed by the user. Here is my code:
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
if (CommonVariables.LoggedIn)
{
CommonVariables.LoggedIn = false;
string jsonPayload = "{\"user_id\":\"" + CommonVariables.AuthenticateUserResponseDetails.user.id + "\"}";
HttpClient client = new HttpClient();
string postUrl = CommonVariables.SERVER + CommonVariables.LogOut;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, postUrl);
//encrypt tase
EDecrypt encrypt = new EDecrypt();
jsonPayload = encrypt.AES_Encrypt(jsonPayload, CommonVariables.EncryptionKey);
request.Content = new StreamContent(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonPayload)));
var result = await client.SendAsync(request);
string response = string.Empty;
}
//TODO: Save application state and stop any background activity
deferral.Complete();
}
This works for me well so when my user closes the app in their device the function is called and they are logged out. However my issue the function also logs the user out when they minimise the app or put the app to the background and go into another app. So how can I adjust my code so that my logout function only works when the user shuts down the app in their device?
When you minimize an app, there are actually 2 things happening:
Visibility change
App suspension
When the user switches from your app to another app, your app is no
longer visible but remains in the Running state until Windows suspends
it. If the user switches away from your app but activates or switches
back to it before it can suspended, the app remains in the Running
state.
So if a user minimizes/switches to another app and comes back fast enough, your app will keep running and your OnSuspending handler will never execute. While being in the background, the OS will determine when your app goes to suspension and when/if it is terminated (like Hans mentioned in his comment).
So to fix your problem: keep your OnSuspending handler, and handle the app resume event to log back in. This will cover both minimizing and closing.

Windows Store App - Local Toast Notification

This may seem like an odd question, but is there a way to send a local toast notification from a Windows 8 Store App to the machine--and NOT show it on the screen? I have a background task that needs to send a sync request to the UI thread. I have been searching for the better part of 8 hours trying to get different methods to work--and it comes down to this will work for me, but I don't want the request text to show up on the screen when I call it.
I should also add that Toast Notifications WILL be used in the app, so I can't simply turn it off globally, I need only the ones I specify to not show up, to be hidden. Is this possible?
Ideally, I would rather do a Raw Notification, but I can't figure out how to do a local Raw Notification (of if its even possible to simulate it without hitting my API.).
EDIT: Root Problem
My background task is doing work behind the scenes every 15 minutes--to basically send a sync request to the main app. The OnPushNotificationReceived, should capture this and perform a full sync of all data I need: Such as GPS coordinates, checking if "ToDoItems" are nearing due dates and need to be escalated in priority, etc. Among other things, such as checking if there are any documents on the local file system that have been marked as complete and need to be uploaded to Azure file storage, etc.
The answer might be in the OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
args.Cancel = true
From MSDN: https://msdn.microsoft.com/en-us/library/br241295
Cancel:
Read/write Gets or sets whether Windows should perform its default handling of the notification.
You receive the notification and process it in your OnPushNotificationReceived listener, set the cancel to true and voila!
Basically you already processed the notification, so you cancel the default behaviour that is showing the notification.
EDIT CONTENT:
The Raw Notification basically is an empty envelope where you can put any content in any form you want, could be an object, an image, a dictionary... Basically you decide the content to send and obviously the app must know the datamodel to be able to process it.
To create Notifications easily I recommend you this Nuget Package: https://github.com/WindowsNotifications/NotificationsExtensions/tree/master/Windows%208.1%20RT
Example on how to create a toast notifcation:
var toastNoti = ToastContentFactory.CreateToastText02();
toastNoti.TextHeading.Text = "TEXT IN BOLD";
toastNoti.TextBodyWrap.Text = "TEXT IN NORMAL CASE ";
toastNoti.Launch = "NOTIFICATION ARGUMENTS";
var doc = new XmlDocument();
doc.LoadXml(toastNoti.ToString());
var endNotification = new ToastNotification(doc);
endNotification.Tag = "1";
ToastNotificationManager.CreateToastNotifier().Show(endNotification);
Hope this helps. Tell us any result please.

Windows Phone 8 notifications and background tasks

I have searched the official forums and documentation and all other places, but haven't been able to find a concrete answer.
Q. In Windows Phone 8, is it possible for an application to respond to a Push Notification, and perform a task, while it is in the background?
As far as I can understand, for Toast and Tile Notifications, when the app is not in the foreground, there are no hooks at all for it to be able to respond to the incoming message.
I think "raw notifications" are the correct choice for this, since I am not required to update the app tile, or even show a Toast Notification. But, I haven't been able to find an example, or in the documentations, if I can do this.
I have found several links which talk about doing this for Windows store apps, but I want to find out if this can be done for Windows Phone 8.
I have checked this other thread,
Windows Phone 8 Background Task with notifications
Where one of the answer suggests that Whatsapp actually has a hack for this, to download the messages after a push notification is received. So, is the answer to my question, a NO?
Answer to your question is not exactly "NO",
and you are right whatsapp uses hack for this,
whatsapp someyow use AudioAgent, as they are allowed to run in background,
i dont know how exactly they do it, i am also searching for the same answer, let's see if i find something will post here
This has changed in Windows Phone 8.1. From Raw notification overview (Windows Runtime apps)
Receiving a raw notification
There are two avenues through which your app can be receive raw
notifications:
Through notification delivery events while your application is running.
Through background tasks triggered by the raw notification if your app is enabled to run background tasks.
An app can use both mechanisms to receive raw notifications. If an app
implements both the notification delivery event handler and background
tasks that are triggered by raw notifications, the notification
delivery event will take priority when the app is running.
If the app is running, the notification delivery event will take priority over the background task and the app will have the first opportunity to process the notification.
The notification delivery event handler can specify, by setting the event's PushNotificationReceivedEventArgs.Cancel property to true, that the raw notification should not be passed to its background task once the handler exits. If the Cancel property is set to false or is not set (the default value is false), the raw notification will trigger the background task after the notification delivery event handler has done its work.
Here is a complete guide on receiving push notifications in the background for Windows Phone 8.1:
Get a push notifications channel URI:
PushNotificationChannel _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
string ChannelUri = _channel.Uri;
Make sure you actually get the URI by logging it. Save the URI and run this on every app launch as the URI gets updated quite frequently.
Create a Windows Runtime Component project inside your solution:
Right click on solution -> Add -> New Project -> select "Windows Runtime Component (Windows Phone)". Call this project "Tasks" or whatever you prefer.
Create a new class extending an IBackgroundTask inside your newly created project. I called mine "NotificationReceiver":
using Windows.ApplicationModel.Background;
namespace Tasks {
public sealed class NotificationReceiver : IBackgroundTask {
public void Run(IBackgroundTaskInstance taskInstance) {
// TODO: implement your task here
}
}
}
Your task will be implemented here inside "Run" function.
Reference your Runtime Component in your main project:
Click on your Windows Phone project -> right click on "References" -> Add Reference -> Tick your Runtime Component and press OK.
Edit your app manifest:
Double-click on your package manifest -> Declarations -> add "Location" and "Push notification" to Supported task types, add your background task class name to Entry point: mine is called "Tasks.NotificationReceiver". Save your changes.
Unregister and register your background task every time the app is launched. I am giving the complete solution, just call "setupBackgroundTask()":
private void setupBackgroundTask() {
requestAccess();
UnregisterBackgroundTask();
RegisterBackgroundTask();
}
private void RegisterBackgroundTask() {
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
PushNotificationTrigger trigger = new PushNotificationTrigger();
taskBuilder.SetTrigger(trigger);
taskBuilder.TaskEntryPoint = "Tasks.NotificationReceiver";
taskBuilder.Name = "pushTask";
try {
BackgroundTaskRegistration task = taskBuilder.Register();
Logger.log("TASK REGISTERED");
} catch (Exception ex) {
Logger.log("FAILED TO REGISTER TASK");
UnregisterBackgroundTask();
}
}
private bool UnregisterBackgroundTask() {
foreach (var iter in BackgroundTaskRegistration.AllTasks) {
IBackgroundTaskRegistration task = iter.Value;
if (task.Name == "pushTask") {
task.Unregister(true);
Logger.log("TASK UNREGISTERED");
return true;
}
}
return false;
}
private async void requestAccess() {
BackgroundAccessStatus backgroundStatus = await BackgroundExecutionManager.RequestAccessAsync();
}
Get RawNotification object inside your task:
RawNotification notification = (RawNotification) taskInstance.TriggerDetails;

How to programmatically detect when the OS (Windows) is waking up or going to sleep

Background
My son likes to use his laptop when he's not supposed to and I just thought it would be handy if I could write an application that would email me whenever he opened / closed his laptop.
(I'd even settle for something that notified me when there was network traffic on the machine)
Question
How do you programmatically detect when an OS is waking up or going to sleep? I found this link from this related post. But that covers OS X. I'm looking for the same thing for Windows 7.
(I'd like to do this in Java, if possible, but I'd settle for C#/C++)
Easiest way is not to write any code at all, even though this is stack overflow. Click Start, type Schedule and choose Scheduled Tasks. Set one up (click Create Task) and set a Trigger when the machine is unlocked. For the Action, have it send you an email.
Repeat for startup and when a user logs in, if you want. Done.
You're going to want to create a window and watch for the WM_POWERBROADCAST message (http://msdn.microsoft.com/en-us/library/aa373248%28v=vs.85%29.aspx) and check the wParam for your desired action. For example, your window should receive a WM_POWERBROADCAST with PBT_APMSUSPEND as the wParam when the system is about to enter a suspended state (i.e. closing a laptop). Resuming seems to have a few different wParam values: PBT_APMRESUMESUSPEND, PBT_APMRESUMECRITICAL and PBT_APMRESUMEAUTOMATIC
I search for a long time and found that this was the best way, the 'Sleep'-event was never working before:
private ManagementEventWatcher managementEventWatcher;
private readonly Dictionary<string, string> powerValues = new Dictionary<string, string>
{
{"4", "Entering Suspend"},
{"7", "Resume from Suspend"},
{"10", "Power Status Change"},
{"11", "OEM Event"},
{"18", "Resume Automatic"}
};
public void InitPowerEvents()
{
var q = new WqlEventQuery();
var scope = new ManagementScope("root\\CIMV2");
q.EventClassName = "Win32_PowerManagementEvent";
managementEventWatcher = new ManagementEventWatcher(scope, q);
managementEventWatcher.EventArrived += PowerEventArrive;
managementEventWatcher.Start();
}
private void PowerEventArrive(object sender, EventArrivedEventArgs e)
{
foreach (PropertyData pd in e.NewEvent.Properties)
{
if (pd == null || pd.Value == null) continue;
var name = powerValues.ContainsKey(pd.Value.ToString())
? powerValues[pd.Value.ToString()]
: pd.Value.ToString();
Console.WriteLine("PowerEvent:"+name);
}
}
public void Stop()
{
managementEventWatcher.Stop();
}
A very simple, perhaps crude, but effective way may be to have a program with a timer firing every minute. If the timer fires and it's been, say, 5 minutes of real time since its last execution then you can likely assume that the computer was sleeping since it's unlikely that your thread was unable to be scheduled for so long.
The other reason for the difference may be a clock adjustment, like DST or a manual change, but that kind of "noise" should be very low, in your scenario.
You could write a simple app and register it as a Windows service, to be started automatically at system startup. This app could then do whatever you want when it starts. And if it's a proper Windows app, it can register to get notification about impending system shutdown too (I don't remember the details but I implemented this in a C++ MFC app many years ago).
If you prefer Java, you could register your app as a service via a suitable service wrapper like Tanuki (it seems they have a free Community License option). Although this might be overkill. And it may be possible to get notification about the JVM shutting down when the system is closing (but I have no concrete experience with this).
http://www.pinvoke.net/default.aspx/powrprof.CallNtPowerInformation - Check out the link. It has almost all win32api for all windows function. You can call power management feature directly in your windows 7 laptop. For that create a Windows Service , that will use these specific api to notify the machine state.

Categories

Resources