public async void PerformNotifications(object autoEvent) { await semaphoreSlim.WaitAsync(); // working as a lock (){} try { var userNotifications = await listener.GetNotificationsAsync(NotificationKinds.Toast); foreach (UserNotification userNotification in userNotifications) { var waNotification = new WaNotification(userNotification); if (Helpers.IsValid(waNotification)) { var passed = await ProcessNotification(waNotification); if (passed) { listener.RemoveNotification(userNotification.Id); } } } } catch (Exception e) { ConsoleProxy.WriteLine(null, ConsoleColor.DarkRed, e.Message); } finally { semaphoreSlim.Release(); } }
private async void Listener_NotificationChanged(UserNotificationListener sender, UserNotificationChangedEventArgs args) { IReadOnlyList <UserNotification> notifs = await sender.GetNotificationsAsync(NotificationKinds.Toast); Debug.WriteLine("--------------NEW Event Received----------------"); foreach (var notif in notifs) { NotificationBinding toastBinding = notif.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric); if (toastBinding != null) { // And then get the text elements from the toast binding IReadOnlyList <AdaptiveNotificationText> textElements = toastBinding.GetTextElements(); // Treat the first text element as the title text string titleText = textElements.FirstOrDefault()?.Text; // We'll treat all subsequent text elements as body text, // joining them together via newlines. string bodyText = string.Join("\n", textElements.Skip(1).Select(t => t.Text)); string payload = "App: " + notif.AppInfo.DisplayInfo.DisplayName + " => Title: " + titleText + ", Body: " + bodyText; Debug.WriteLine(payload); _listItems.Add(new NotificationCenterData() { AppName = notif.AppInfo.DisplayInfo.DisplayName, Title = titleText, Body = bodyText }); } } await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { NotificationListView.ItemsSource = _listItems; }); }
private async void Button_Click(object sender, RoutedEventArgs e) { UserNotificationListener c = UserNotificationListener.Current; UserNotificationListenerAccessStatus x = await c.RequestAccessAsync(); var toast = await c.GetNotificationsAsync(Windows.UI.Notifications.NotificationKinds.Toast); foreach (var notif in toast) { var notification = notif.Notification; StringBuilder stringBuilder = new StringBuilder(); var appname = notif.AppInfo.DisplayInfo.DisplayName; if (appname != "Mail") { continue; } foreach (NotificationBinding binding in notification.Visual.Bindings) { foreach (var textElelment in binding.GetTextElements()) { stringBuilder.Append(textElelment.Text); stringBuilder.Append("\n"); } ContentDialog mydialog = new ContentDialog { Title = appname, Content = stringBuilder.ToString(), CloseButtonText = "ok" }; ContentDialogResult contentDialogResult = await mydialog.ShowAsync(); } } }
public async void UpdateNotifications() { try { IReadOnlyList <UserNotification> notifsInPlatform = await _listener.GetNotificationsAsync(NotificationKinds.Toast); // Reverse their order since the platform returns them with oldest first, we want newest first notifsInPlatform = notifsInPlatform.Reverse().ToList(); // First remove any notifications that no longer exist for (int i = 0; i < this.Notifications.Count; i++) { UserNotification existingNotif = this.Notifications[i]; // If not in platform anymore, remove from our list if (!notifsInPlatform.Any(n => n.Id == existingNotif.Id)) { this.Notifications.RemoveAt(i); i--; } } // Now our list only contains notifications that exist, // but it might be missing new notifications. for (int i = 0; i < notifsInPlatform.Count; i++) { UserNotification platNotif = notifsInPlatform[i]; int indexOfExisting = FindIndexOfNotification(platNotif.Id); // If we have an existing if (indexOfExisting != -1) { // And if it's in the wrong position if (i != indexOfExisting) { // Move it to the right position this.Notifications.Move(indexOfExisting, i); } // Otherwise, leave it in its place } // Otherwise, notification is new else { // Insert at that position this.Notifications.Insert(i, platNotif); } } } catch (Exception ex) { Error = "Error updating notifications: " + ex.ToString(); } }
public static int GetToastCount() { int ret = 0; try { // Get the listener UserNotificationListener listener = UserNotificationListener.Current; var n = listener.GetNotificationsAsync(NotificationKinds.Toast); IReadOnlyList <UserNotification> l; try { while (n.Status != AsyncStatus.Completed) { Thread.Sleep(10); } l = n.GetResults(); ret = l.Count; } finally { n.Close(); } } catch { } return(ret); }
public static async Task SyncNotifications() { // Get the listener UserNotificationListener listener = UserNotificationListener.Current; // Get all the current notifications from the platform IReadOnlyList <UserNotification> userNotifications = await listener.GetNotificationsAsync(NotificationKinds.Toast); // Obtain the notifications that our wearable currently has displayed List <uint> wearableNotificationIds = GetNotificationsOnWearable(userNotifications); // For each notification in the platform foreach (UserNotification userNotification in userNotifications) { // If we've already displayed this notification if (wearableNotificationIds.Contains(userNotification.Id)) { } // Othwerise it's a new notification else { // Display it on the Wearable SendNotificationToWearable(userNotification); } } }
private async void Page_Loaded(object sender, RoutedEventArgs e) { // go to loading page Navigation.IsEnabled = false; _ = ContentFrame.Navigate(typeof(Pages.LoadingPage), null); // check permissions try { Conf.Log("detecting permissions..."); var accessStatus = await Listener.RequestAccessAsync(); switch (accessStatus) { case UserNotificationListenerAccessStatus.Allowed: Conf.Log("permission granted!", LogLevel.Complete); IsListenerActive = true; IsPermissionGranted = true; var initialList = await Listener.GetNotificationsAsync(NotificationKinds.Toast); Conf.Log($"loading {initialList.Count} notification(s)..."); foreach (var notif in initialList) { Conf.CurrentConf.AddApp(new AppInfo(notif.AppInfo) { ForwardingEnabled = !Conf.CurrentConf.MuteNewApps }); } Notifications.AddRange(initialList); Listener.NotificationChanged += NotificationHandler; Conf.Log("notification listener activated.", LogLevel.Complete); StartUploadWorker(); break; default: Conf.Log("permission not granted, no exceptions thrown.", LogLevel.Warning); await NoPermissionDialog(); break; } } catch (Exception ex) { Conf.Log($"notification listener failed: {ex.Message}, HRESULT 0x{ex.HResult:x}", LogLevel.Error); await NoPermissionDialog(ex.Message); } Navigation.SelectedItem = HomePageItem; Navigation.IsEnabled = true; // wait 1 sec var paneCloser = new Thread(async() => { Thread.Sleep(1000); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { Navigation.IsPaneOpen = false; }); }); paneCloser.Start(); }
protected override async void OnBackgroundActivated(BackgroundActivatedEventArgs args) { var deferral = args.TaskInstance.GetDeferral(); switch (args.TaskInstance.Task.Name) { case "UserNotificationChanged": // Call your own method to process the new/removed notifications // The next section of documentation discusses this code //await MyWearableHelpers.SyncNotifications(); var frame = (Frame)Window.Current.Content; var page = (MainPage)frame.Content; UserNotificationListener listener = UserNotificationListener.Current; IReadOnlyList <UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast); double x = notifs.Count; if (x > 0) { UserNotification notif = notifs[0]; // Get the app's display name string appDisplayName = notif.AppInfo.DisplayInfo.DisplayName; page.setText(appDisplayName); string message = notif.Notification.ToString(); page.setText(message); string titleText = ""; string bodyText = ""; NotificationBinding toastBinding = notif.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric); if (toastBinding != null) { // And then get the text elements from the toast binding IReadOnlyList <AdaptiveNotificationText> textElements = toastBinding.GetTextElements(); // Treat the first text element as the title text titleText = textElements.FirstOrDefault()?.Text; // We'll treat all subsequent text elements as body text, // joining them together via newlines. bodyText = string.Join("\n", textElements.Skip(1).Select(t => t.Text)); bodyText += ""; } page.setText(titleText); page.setText(bodyText); // Get the app's logo BitmapImage appLogo = new BitmapImage(); RandomAccessStreamReference appLogoStream = notif.AppInfo.DisplayInfo.GetLogo(new Size(16, 16)); await appLogo.SetSourceAsync(await appLogoStream.OpenReadAsync()); } break; } deferral.Complete(); }
private async void GetList_Click(object sender, RoutedEventArgs e) { IReadOnlyList <UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast); // NotificationsList.ItemsSource = notifs; foreach (var item in notifs) { Debug.WriteLine(item.Notification.Visual.Bindings[0].GetTextElements()); } Debug.WriteLine("Список получен"); }
private static async Task NowTask() { UserNotificationListener listener = UserNotificationListener.Current; UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync(); switch (accessStatus) { case UserNotificationListenerAccessStatus.Allowed: Console.WriteLine("notifications allowed"); break; case UserNotificationListenerAccessStatus.Denied: Console.WriteLine("notifications denied"); break; case UserNotificationListenerAccessStatus.Unspecified: Console.WriteLine("notifications something else"); break; } IReadOnlyList <UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast); List <string> combined = new List <string>(); foreach (var notif in notifs) { NotificationBinding toastBinding = notif.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric); if (toastBinding != null) { // And then get the text elements from the toast binding IReadOnlyList <AdaptiveNotificationText> textElements = toastBinding.GetTextElements(); // Treat the first text element as the title text string titleText = textElements.FirstOrDefault()?.Text; // We'll treat all subsequent text elements as body text, // joining them together via newlines. string bodyText = string.Join("\n", textElements.Skip(1).Select(t => t.Text)); //Console.WriteLine("\nhead: " + titleText); //Console.WriteLine("body: " + bodyText); combined.Add(titleText); combined.Add(bodyText); } } Console.WriteLine("\nWritten to: " + Settings.notificationCacheFileLocation); await File.WriteAllLinesAsync(Settings.notificationCacheFileLocation, combined); //clears windows messages | throws an AggregateException, I have no idea why, nothing from google, too //listener.ClearNotifications(); Environment.Exit(0); }
private async void Show_Dialog_Messages() { headers.Text = ""; UserNotificationListener c = UserNotificationListener.Current; UserNotificationListenerAccessStatus x = await c.RequestAccessAsync(); int i = 100; var toast = await c.GetNotificationsAsync(Windows.UI.Notifications.NotificationKinds.Toast); foreach (var notif in toast) { var notification = notif.Notification; StringBuilder stringBuilder = new StringBuilder(); var appname = notif.AppInfo.DisplayInfo.DisplayName; if (appname != "Mail") { continue; } foreach (NotificationBinding binding in notification.Visual.Bindings) { foreach (var textElelment in binding.GetTextElements()) { stringBuilder.Append(textElelment.Text); stringBuilder.Append("\n"); } SendToast(appname + "\n" + stringBuilder.ToString(), i.ToString()); headers.Text = headers.Text + "\n" + stringBuilder.ToString(); //ContentDialog mydialog = new ContentDialog //{ // Title = appname, // Content = stringBuilder.ToString(), // CloseButtonText = "ok" //}; //try //{ // ContentDialogResult contentDialogResult = await mydialog.ShowAsync(); //} //catch (System.Runtime.InteropServices.COMException e) //{ // SendToast( // e.Message); //} i = i + 1; } } }
private async Task <UserNotification> GetNotification() { // Get the listener UserNotificationListener listener = UserNotificationListener.Current; // Get the toast notifications IReadOnlyList <UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast); return(notifs.First()); // For each notification in the platform foreach (UserNotification userNotification in notifs) { // If we've already displayed this notification //DisplayToast(userNotification); } }
private async void Form1_LoadAsync(object sender, EventArgs e) { if (ApiInformation.IsTypePresent("Windows.UI.Notifications.Management.UserNotificationListener")) { // Listener supported! } else { // Older version of Windows, no Listener } // Get the listener UserNotificationListener listener = UserNotificationListener.Current; // And request access to the user's notifications (must be called from UI thread) UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync(); switch (accessStatus) { // This means the user has granted access. case UserNotificationListenerAccessStatus.Allowed: // Yay! Proceed as normal break; // This means the user has denied access. // Any further calls to RequestAccessAsync will instantly // return Denied. The user must go to the Windows settings // and manually allow access. case UserNotificationListenerAccessStatus.Denied: // Show UI explaining that listener features will not // work until user allows access. break; // This means the user closed the prompt without // selecting either allow or deny. Further calls to // RequestAccessAsync will show the dialog again. case UserNotificationListenerAccessStatus.Unspecified: // Show UI that allows the user to bring up the prompt again break; } IReadOnlyList <UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast); }
private async void SyncNotifications() { // Get the listener UserNotificationListener listener = UserNotificationListener.Current; // And request access to the user's notifications (must be called from UI thread) UserNotificationListenerAccessStatus notificationListenerAccessStatus = await listener.RequestAccessAsync(); switch (notificationListenerAccessStatus) { // This means the user has granted access. case UserNotificationListenerAccessStatus.Allowed: // Get the toast notifications notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast); Debug.WriteLine("Size of current notification buffer: " + notifs.Count()); AcHelper.ProcessNotification(notifs.LastOrDefault()); break; // This means the user has denied access. // Any further calls to RequestAccessAsync will instantly // return Denied. The user must go to the Windows settings // and manually allow access. case UserNotificationListenerAccessStatus.Denied: Debug.WriteLine("UserNotificationListenerAccessStatus.Denied"); // Show UI explaining that listener features will not // work until user allows access. break; // This means the user closed the prompt without // selecting either allow or deny. Further calls to // RequestAccessAsync will show the dialog again. case UserNotificationListenerAccessStatus.Unspecified: Debug.WriteLine("UserNotificationListenerAccessStatus.Unspecified"); // Show UI that allows the user to bring up the prompt again break; } }
public static async Task SyncNotifications() { List <uint> notificationIds = CurrentNotificationIds; List <uint> toBeRemoved = new List <uint>(notificationIds); string[] blockedAppIds = Regex.Split((string)Settings.Get("BLOCKEDAPPIDS", ""), "\r\n|\r|\n"); UserNotificationListener listener = UserNotificationListener.Current; IReadOnlyList <UserNotification> userNotifications = await listener.GetNotificationsAsync(NotificationKinds.Toast); foreach (UserNotification userNotification in userNotifications) { if (notificationIds.Contains(userNotification.Id)) { toBeRemoved.Remove(userNotification.Id); } else { if (!blockedAppIds.Contains((string)userNotification.AppInfo.AppUserModelId)) { _ = AddNotification(userNotification); notificationIds.Add(userNotification.Id); } } } foreach (uint id in toBeRemoved) { _ = RemoveNotification(id); notificationIds.Remove(id); } CurrentNotificationIds = notificationIds; return; }
private async Task UpdateNotiFile() { // Check Permissions if (!ApiInformation.IsTypePresent("Windows.UI.Notifications.Management.UserNotificationListener")) { Debug.WriteLine("IsTypePresent: NG"); return; } Debug.WriteLine("IsTypePresent: OK"); UserNotificationListener listener = UserNotificationListener.Current; Debug.Write("listener: "); Debug.WriteLine(listener); while (true) { // Read Notifications try { UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync(); Debug.Write("accessStatus: "); Debug.WriteLine(accessStatus); if (accessStatus != UserNotificationListenerAccessStatus.Allowed) { Debug.WriteLine("アクセス拒否"); return; } Debug.WriteLine("アクセス許可"); IReadOnlyList <UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast); // Write to Download/App3 Windows.Storage.StorageFile file = await DownloadsFolder.CreateFileAsync("notifications.txt"); // await Windows.Storage.FileIO.WriteTextAsync(file, "Example of writing a string\r\n"); // Append a list of strings, one per line, to the file var listOfStrings = new List <string> { }; foreach (var n in notifs) { NotificationBinding toastBinding = n.Notification.Visual.GetBinding(KnownNotificationBindings.ToastGeneric); if (toastBinding != null) { IReadOnlyList <AdaptiveNotificationText> textElements = toastBinding.GetTextElements(); string titleText = textElements.FirstOrDefault()?.Text; string bodyText = string.Join("\n", textElements.Skip(1).Select(t => t.Text)); Debug.Write("Title:"); Debug.WriteLine(titleText); Debug.Write("Body:"); Debug.WriteLine(bodyText); int MsgType = GetNotiType(n.AppInfo.DisplayInfo.DisplayName); if (MsgType != -1) { listOfStrings.Add(String.Format("{0}", MsgType)); } // await Windows.Storage.FileIO.WriteTextAsync(file, String.Format("{0}, {1}\n", n.AppInfo.DisplayInfo.DisplayName, titleText)); } } await Windows.Storage.FileIO.AppendLinesAsync(file, listOfStrings); // each entry in the list is written to the file on its own line. await Task.Delay(TimeSpan.FromSeconds(1)); } catch (Exception ex) { } } }
public static IAsyncOperation <IReadOnlyList <UserNotification> > RetriveNotificationsAsync() { return(UserNotificationListener.GetNotificationsAsync(NotificationKinds.Toast)); }
async Task <int> getAccess() { //await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); // Get the listener UserNotificationListener listener = UserNotificationListener.Current; // And request access to the user's notifications (must be called from UI thread) UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync(); switch (accessStatus) { // This means the user has granted access. case UserNotificationListenerAccessStatus.Allowed: if (!BackgroundTaskRegistration.AllTasks.Any(k => k.Value.Name.Equals("UserNotificationChanged"))) { // Specify the background task var builder = new BackgroundTaskBuilder() { Name = "UserNotificationChanged" }; // Set the trigger for Listener, listening to Toast Notifications builder.SetTrigger(new UserNotificationChangedTrigger(NotificationKinds.Toast)); // Register the task builder.Register(); } IReadOnlyList <UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast); IReadOnlyList <UserNotification> notifsUn = await listener.GetNotificationsAsync(NotificationKinds.Unknown); double notifCount = notifs.Count; if (notifCount > 0) { UserNotification notif = notifs[0]; string message = notif.Notification.ToString(); if (notif.AppInfo.DisplayInfo.DisplayName != null) { // Get the app's display name string appDisplayName = notif.AppInfo.DisplayInfo.DisplayName; } // Get the app's logo BitmapImage appLogo = new BitmapImage(); RandomAccessStreamReference appLogoStream = notif.AppInfo.DisplayInfo.GetLogo(new Size(16, 16)); await appLogo.SetSourceAsync(await appLogoStream.OpenReadAsync()); } // Yay! Proceed as normal break; // This means the user has denied access. // Any further calls to RequestAccessAsync will instantly // return Denied. The user must go to the Windows settings // and manually allow access. case UserNotificationListenerAccessStatus.Denied: // Show UI explaining that listener features will not // work until user allows access. break; // This means the user closed the prompt without // selecting either allow or deny. Further calls to // RequestAccessAsync will show the dialog again. case UserNotificationListenerAccessStatus.Unspecified: // Show UI that allows the user to bring up the prompt again break; } int i = 1; return(i); }
public static IAsyncAction UpdateNotifications() { return(Task.Run(async() => { try { // Get the toast notifications var notifsInPlatform = await _listener.GetNotificationsAsync(NotificationKinds.Toast); // Reverse their order since the platform returns them with oldest first, we want newest first notifsInPlatform = notifsInPlatform.Reverse().ToList(); // First remove any notifications that no longer exist for (var i = 0; i < Notifications.Count; i++) { var existingNotif = Notifications[i]; // If not in platform anymore, remove from our list if (notifsInPlatform.Any(n => n.Id == existingNotif.Id)) { continue; } Notifications.RemoveAt(i); i--; if ((bool)LocalSettings.Values["IsBackgroundTaskActive"] && existingNotif.AppInfo.PackageFamilyName != PackageFamilyName) { SendNotification(Type.Remove, existingNotif); } } // Now our list only contains notifications that exist, // but it might be missing new notifications. for (var i = 0; i < notifsInPlatform.Count; i++) { var platNotif = notifsInPlatform[i]; var indexOfExisting = FindIndexOfNotification(platNotif.Id); // If we have an existing if (indexOfExisting != -1) { // And if it's in the wrong position if (i == indexOfExisting) { continue; } // Move it to the right position Notifications.Move(indexOfExisting, i); if ((bool)LocalSettings.Values["IsBackgroundTaskActive"] && platNotif.AppInfo.PackageFamilyName != PackageFamilyName) { SendNotification(Type.Add, platNotif); } // Otherwise, leave it in its place } // Otherwise, notification is new else { // Insert at that position Notifications.Insert(i, platNotif); if (LocalSettings.Values["newSettings"] != null && (bool)LocalSettings.Values["newSettings"]) { _oldData = await ReadNotificationApps(); LocalSettings.Values["newSettings"] = false; } if (_notificationApps.All(x => x.Key != platNotif.AppInfo.AppUserModelId) && platNotif.AppInfo.PackageFamilyName != PackageFamilyName) { var notificationApp = new NotificationApp { Key = platNotif.AppInfo.AppUserModelId, Name = platNotif.AppInfo.DisplayInfo.DisplayName, Allowed = true }; var stream = Stream.Null; try { var icon = await platNotif.AppInfo.DisplayInfo.GetLogo(new Size(16, 16)).OpenReadAsync(); stream = icon.AsStreamForRead(); } catch (Exception) { // ignored } var buffer = new byte[stream.Length]; await stream.ReadAsync(buffer, 0, buffer.Length); notificationApp.IconData = buffer; _notificationApps.Add(notificationApp); var newData = notificationApp.Serialize(); var data = new byte[_oldData.Length + newData.Length]; System.Buffer.BlockCopy(_oldData, 0, data, 0, _oldData.Length); System.Buffer.BlockCopy(newData, 0, data, _oldData.Length, newData.Length); await FileIO.WriteBytesAsync(_notificationAppsFile, data); } if ((bool)LocalSettings.Values["IsBackgroundTaskActive"] && platNotif.AppInfo.PackageFamilyName != PackageFamilyName && _notificationApps.Any(x => x.Key == platNotif.AppInfo.AppUserModelId && x.Allowed)) { SendNotification(Type.Add, platNotif); } } } } catch (Exception) { // ignored } }).AsAsyncAction()); }