コード例 #1
0
        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);
        }
コード例 #2
0
ファイル: MainPage.xaml.cs プロジェクト: Anushiravani/Minista
        private async void MainPageLoaded(object sender, RoutedEventArgs e)
        {
            CreateConfig();


            var coreTitleBar = CoreApplication.GetCurrentView().TitleBar;

            coreTitleBar.ExtendViewIntoTitleBar = true;
            //AppTitleBar.Height = coreTitleBar.Height;
            coreTitleBar.LayoutMetricsChanged += CoreTitleBarLayoutMetricsChanged;
            // Set XAML element as a draggable region.
            //AppTitleBar.Height = coreTitleBar.Height;

            UpdateTitleBarLayout(coreTitleBar);
            Window.Current.SetTitleBar(AppTitleBarORG);
            if (InstaApi == null || InstaApi != null && !InstaApi.IsUserAuthenticated)
            {
                SetStackPanelTitleVisibility(Visibility.Collapsed);
                NavigationService.Navigate(typeof(Views.Sign.SignInView));
            }
            else
            {
                NavigateToMainView();
            }

            if (!SettingsHelper.Settings.AskedAboutPosition)
            {
                SettingsGrid.Visibility = Visibility.Visible;
            }
            if (ScreenOnRequest != null)
            {
                ScreenOnRequest.RequestActive();
            }
            CheckLicense();
            try
            {
                if (Passcode.IsEnabled)
                {
                    PassCodeView.Visibility = Visibility.Visible;
                    LockControl.Visibility  = Visibility.Visible;
                }
                else
                {
                    PassCodeView.Visibility = Visibility.Collapsed;
                    LockControl.Visibility  = Visibility.Collapsed;
                }
            }
            catch { }
            try
            {
                await BackgroundExecutionManager.RequestAccessAsync();
            }
            catch { }
            try
            {
                UserNotificationListener listener = UserNotificationListener.Current;
                await listener.RequestAccessAsync();
            }
            catch { }
        }
コード例 #3
0
ファイル: MainPage.xaml.cs プロジェクト: PavelSHK/Notify
        public async void SetListener()
        {
            listener = UserNotificationListener.Current;

            UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync();

            switch (accessStatus)
            {
            case UserNotificationListenerAccessStatus.Allowed:
                GetAccessBackgroundTask();
                Debug.WriteLine("Уведомления доступны");

                break;

            case UserNotificationListenerAccessStatus.Denied:
                StatusUpdate("Уведомления недоступны. Откройте");
                break;

            case UserNotificationListenerAccessStatus.Unspecified:
                Debug.WriteLine("Неизвестно");
                break;

            default:
                Status.Text = "Уведомления недоступны";
                break;
            }
        }
コード例 #4
0
        public NotificationListener(IMediator mediator, IList <INotificationHandler> notificationHandlers)
        {
            _mediator             = mediator;
            _notificationHandlers = notificationHandlers;

            _listener = UserNotificationListener.Current;
        }
コード例 #5
0
        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);
                }
            }
        }
コード例 #6
0
        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();
                }
            }
        }
コード例 #7
0
        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;
            });
        }
コード例 #8
0
        public static bool RequestAccess(out bool denied)
        {
            bool ret = false;

            denied = false;

            // Get the listener
            UserNotificationListener listener = UserNotificationListener.Current;

            // And request access to the user's notifications (must be called from UI thread)
            var t = listener.RequestAccessAsync();

            UserNotificationListenerAccessStatus accessStatus;

            try
            {
                while (t.Status != AsyncStatus.Completed)
                {
                    Thread.Sleep(10);
                }
                accessStatus = t.GetResults();
            }
            finally
            {
                t.Close();
            }

            switch (accessStatus)
            {
            // This means the user has granted access.
            case UserNotificationListenerAccessStatus.Allowed:

                // Yay! Proceed as normal
                ret = true;
                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.
                denied = true;
                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;
            }

            return(ret);
        }
コード例 #9
0
        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();
        }
コード例 #10
0
        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);
        }
コード例 #11
0
 private void NotificationListener_NotificationChanged(UserNotificationListener sender, UserNotificationChangedEventArgs args)
 {
     switch (args.ChangeKind)
     {
     case UserNotificationChangedKind.Added:
         UserNotification notification = sender.GetNotification(args.UserNotificationId);
         if (notification != null && notification.AppInfo.AppUserModelId == WINDOWS_SYSTEM_TOAST_CALLING)
         {
             sender.RemoveNotification(notification.Id);
         }
         break;
     }
 }
コード例 #12
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;
                }
            }
        }
コード例 #13
0
        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);
            }
        }
コード例 #14
0
        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);
        }
コード例 #15
0
        public async void SetListener()
        {
            listener = UserNotificationListener.Current;

            UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync();

            switch (accessStatus)
            {
            case UserNotificationListenerAccessStatus.Allowed:
                Debug.WriteLine("Уведомления доступны");
                break;

            case UserNotificationListenerAccessStatus.Denied:
                Debug.WriteLine("Уведомления недоступны");
                break;

            case UserNotificationListenerAccessStatus.Unspecified:
                Debug.WriteLine("Неизвестно");
                break;
            }
        }
コード例 #16
0
        private async void OnNotificationChanged(UserNotificationListener sender, UserNotificationChangedEventArgs args)
        {
            if (args.ChangeKind == UserNotificationChangedKind.Added)
            {
                var notification = await _mediator.Send(new QueryNotificationRequest { Id = args.UserNotificationId });

                if (notification != null)
                {
                    var eventArgs = new NotificationEventArgs {
                        Notification = notification
                    };
                    foreach (var notificationHandler in _notificationHandlers.ToList())
                    {
                        if (eventArgs.Handled)
                        {
                            break;
                        }
                        notificationHandler.OnHandleChatHeadNotification(eventArgs);
                    }
                }
            }
        }
コード例 #17
0
        public async void CheckNotificationAccess()
        {
            // 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
                isAccessGranted = true;
                // Subscribe to foreground event
                listener.NotificationChanged += Listener_NotificationChanged;
                // Get the toast notifications
                //IReadOnlyList<UserNotification> notifs = await listener.GetNotificationsAsync(NotificationKinds.Toast);
                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;
            }
        }
コード例 #18
0
        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;
            }
        }
コード例 #19
0
ファイル: WidgetPhone.xaml.cs プロジェクト: lulzzz/Miriot
        private async Task <bool> AskRequest()
        {
            // 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:
                return(true);

                // 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;
            }

            return(false);
        }
コード例 #20
0
        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;
        }
コード例 #21
0
        public static async Task <bool> GetNotificationPermission()
        {
            UserNotificationListener             listener     = UserNotificationListener.Current;
            UserNotificationListenerAccessStatus accessStatus = await listener.RequestAccessAsync();

            switch (accessStatus)
            {
            case UserNotificationListenerAccessStatus.Allowed:
                Debug.WriteLine("Notification Access ALLOWED!");
                return(true);

            case UserNotificationListenerAccessStatus.Denied:
                Debug.WriteLine("Notification Access DENIED!");
                return(false);

            case UserNotificationListenerAccessStatus.Unspecified:
                Debug.WriteLine("Notification Access UNSPECIFIED!");
                return(false);

            default:
                Debug.WriteLine("This shouldn't be happening!");
                return(false);
            }
        }
コード例 #22
0
        private async void Listener_NotificationChanged(UserNotificationListener sender, UserNotificationChangedEventArgs args)
        {
            var userNotifications = await listener.GetNotificationsAsync(NotificationKinds.Toast);

            foreach (UserNotification userNotification in userNotifications)
            {
                if (userNotification.Id == args.UserNotificationId)
                {
                    var waNotification = new WaNotification(userNotification);

                    ConsoleProxy.WriteLine(null, ConsoleColor.Yellow, $"Notification arrived " +
                                           $"at: {DateTime.Now.ToLocalTime().ToShortTimeString()}, id: {args.UserNotificationId}");
                    if (Helpers.IsValid(waNotification))
                    {
                        var passed = await ProcessNotification(waNotification);

                        if (passed)
                        {
                            listener.RemoveNotification(userNotification.Id);
                        }
                    }
                }
            }
        }
コード例 #23
0
 public Notifications()
 {
     // Get the listener
     this._listener = UserNotificationListener.Current;
 }
コード例 #24
0
        public static async void RegisterBackgroundTask()
        {
            // TODO: Request/check Listener access via UserNotificationListener.Current.RequestAccessAsync

            // 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.
                ContentDialog diniedDialog = new ContentDialog()
                {
                    Title           = "Access denied",
                    Content         = "Access request is denied. Go to Windows Settings and allow access manually.",
                    CloseButtonText = "Ok"
                };
                await diniedDialog.ShowAsync();

                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;
            }

            // TODO: request / check background task access via backgroundexecutionmanager.requestaccessasync
            // https://docs.microsoft.com/en-us/windows/uwp/launch-resume/run-a-background-task-on-a-timer-
            var requeststatus = await BackgroundExecutionManager.RequestAccessAsync();

            if (requeststatus != BackgroundAccessStatus.AlwaysAllowed)
            {
                // depending on the value of requeststatus, provide an appropriate response
                // such as notifying the user which functionality won't work as expected
                ContentDialog deniedDialog = new ContentDialog()
                {
                    Title             = "Notice",
                    Content           = "Background access is not \"Always allowed\". Go to Windows Settings and allow access manually.",
                    PrimaryButtonText = "Go to Settings",
                    CloseButtonText   = "Back"
                };
                deniedDialog.PrimaryButtonClick += async(s, a) =>
                {
                    var success = await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:batterysaver-usagedetails"));
                };
                await deniedDialog.ShowAsync();
            }

            // If background task isn't registered yet
            if (!BackgroundTaskRegistration.AllTasks.Any(i => i.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();
            }
        }
コード例 #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NewAlertCharacteristic" /> class.
 /// </summary>
 /// <param name="characteristic">The characteristic that this wraps</param>
 public NewAlertCharacteristic(GattLocalCharacteristic characteristic, GenericGattService service) : base(characteristic, service)
 {
     notificationListener = UserNotificationListener.Current;
 }
コード例 #26
0
        private async void Initialize()
        {
            try
            {
                BackgroundTaskHelper.RegisterIfNotRegistered();
            }

            catch (Exception ex)
            {
                Error = "Failed to register background task: " + ex.ToString();
                return;
            }

            var picLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);

            string        path   = picLibrary.SaveFolder.Path;
            string        name   = "ZLog.csv";
            StorageFolder folder = KnownFolders.PicturesLibrary;
            var           tRes   = folder.TryGetItemAsync(name);
            await Task.Delay(1000);

            var outputFile = tRes.GetResults();

            if (outputFile is null == false)
            {
                StorageFolder storage  = KnownFolders.PicturesLibrary;
                StorageFile   zlogFile = await storage.GetFileAsync(name);

                await zlogFile.DeleteAsync();

                await Task.Delay(1000);

                await storage.CreateFileAsync(name, CreationCollisionOption.OpenIfExists);

                await Task.Delay(1000);
            }



            try
            {
                _listener = UserNotificationListener.Current;

                // Check listener status
                var accessStatus = await _listener.RequestAccessAsync();

                switch (accessStatus)
                {
                case UserNotificationListenerAccessStatus.Allowed:
                    // Good, continue through
                    break;

                case UserNotificationListenerAccessStatus.Denied:
                    Error = "Listener permission has been denied. Please go to your settings and allow listener access for this app, then close and re-launch this app.";
                    return;

                default:
                    Error = "Please close and re-open this app. Listener permission hasn't been allowed or denied yet.";
                    return;
                }
            }

            catch (Exception ex)
            {
                Error = "Failed requesting access to Listener: " + ex.ToString();
                return;
            }

            UpdateNotifications();
        }
コード例 #27
0
ファイル: Utils.cs プロジェクト: j2m2/CmisSync
 /// <summary>
 /// Register the component which will receive notifications intended for the end-user.
 /// </summary>
 public static void SetUserNotificationListener(UserNotificationListener listener)
 {
     UserNotificationListener = listener;
 }
コード例 #28
0
        /// <inheritdoc />
        /// <summary>
        /// The entry point of a background task.
        /// </summary>
        /// <param name="taskInstance">The current background task instance.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Get the deferral to prevent the task from closing prematurely
            _deferral = taskInstance.GetDeferral();

            // Setup our onCanceled callback and progress
            _taskInstance           = taskInstance;
            _taskInstance.Canceled += OnCanceled;
            _taskInstance.Progress  = 0;

            // Store a setting so that the app knows that the task is running.
            LocalSettings.Values["IsBackgroundTaskActive"] = true;

            //_periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(PeriodicTimerCallback, TimeSpan.FromSeconds(1));

            _songTitleTimer =
                ThreadPoolTimer.CreatePeriodicTimer(SongTitleTimerCallback, TimeSpan.FromMilliseconds(500));

            _timer = new Timer(TimerCallback, null, 500, 500);

            _listener = UserNotificationListener.Current;

            _notificationAppsFile = await _localFolder.GetFileAsync("notificationApps");

            await Logger.Logger.CreateLogFile();

            _oldData = await ReadNotificationApps();

            _id = 0;

            try
            {
                var details = (RfcommConnectionTriggerDetails)taskInstance.TriggerDetails;
                if (details != null)
                {
                    _socket       = details.Socket;
                    _remoteDevice = details.RemoteDevice;
                    LocalSettings.Values["RemoteDeviceName"] = _remoteDevice.Name;

                    _writer = new DataWriter(_socket.OutputStream);
                    _reader = new DataReader(_socket.InputStream);

                    Logger.Logger.Info("Connected to " + _remoteDevice.Name + "(" + _remoteDevice.BluetoothAddress + ")");

                    await UpdateNotifications();
                }
                else
                {
                    LocalSettings.Values["BackgroundTaskStatus"] = "Trigger details returned null";
                    _deferral.Complete();
                }

                Logger.Logger.Info("Rfcomm Server Task instance");

                await ReceiveDataAsync();
            }
            catch (Exception ex)
            {
                _reader = null;
                _writer = null;
                _socket = null;
                _deferral.Complete();

                Debug.WriteLine("Exception occurred while initializing the connection, hr = " + ex.HResult.ToString("X"));
            }
        }
コード例 #29
0
ファイル: MainPage.xaml.cs プロジェクト: ramtinak/Minista
        private async void MainPageLoaded(object sender, RoutedEventArgs e)
        {
            ThemeHelper.InitTheme(SettingsHelper.Settings.CurrentTheme);
            CreateConfig();
            try
            {
                Focus(FocusState.Pointer);
            }
            catch { }
            var coreTitleBar = CoreApplication.GetCurrentView().TitleBar;

            coreTitleBar.ExtendViewIntoTitleBar = true;
            coreTitleBar.LayoutMetricsChanged  += CoreTitleBarLayoutMetricsChanged;
            UpdateTitleBarLayout(coreTitleBar);
            Window.Current.SetTitleBar(AppTitleBarORG);
            if (InstaApi == null || InstaApi != null && !InstaApi.IsUserAuthenticated)
            {
                SetStackPanelTitleVisibility(Visibility.Collapsed);
                NavigationService.Navigate(typeof(Views.Sign.SignInView));
            }
            else
            {
                NavigateToMainView();
            }

            if (!SettingsHelper.Settings.AskedAboutPosition)
            {
                SettingsGrid.Visibility = Visibility.Visible;
            }
            //if (App.ScreenOnRequest != null)
            //    App.ScreenOnRequest.RequestActive();
            CheckLicense();


            var ver = await IsUsingLatestVersion();

            var aaaabc = await GetLatestVersionNumber();

            try
            {
                if (Passcode.IsEnabled)
                {
                    PassCodeView.Visibility = Visibility.Visible;
                    LockControl.Visibility  = Visibility.Visible;
                }
                else
                {
                    PassCodeView.Visibility = Visibility.Collapsed;
                    LockControl.Visibility  = Visibility.Collapsed;
                }
            }
            catch { }
            try
            {
                await BackgroundExecutionManager.RequestAccessAsync();
            }
            catch { }
            try
            {
                UserNotificationListener listener = UserNotificationListener.Current;
                await listener.RequestAccessAsync();
            }
            catch { }
        }
コード例 #30
0
ファイル: Utils.cs プロジェクト: pcreignou/CmisSync
 /// <summary>
 /// Register the component which will receive notifications intended for the end-user.
 /// </summary>
 public static void SetUserNotificationListener(UserNotificationListener listener)
 {
     UserNotificationListener = listener;
 }
コード例 #31
0
        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);
        }