Search code examples
c#xamluwpnotificationstoast

UWP Notification Toast Activated, Update and Expire


I have a toast implemented in the code below:

    public void ShowToast(Music music)
    {
        var toastContent = new ToastContent()
        {
            Visual = new ToastVisual()
            {
                BindingGeneric = new ToastBindingGeneric()
                {
                    Children =
                    {
                        new AdaptiveText()
                        { 
                            Text = string.IsNullOrEmpty(music.Artist) ?
                                   string.IsNullOrEmpty(music.Album) ? music.Name : string.Format("{0} - {1}", music.Name, music.Album) :
                                   string.Format("{0} - {1}", music.Name, string.IsNullOrEmpty(music.Artist) ? music.Album : music.Artist)
                        },
                        new AdaptiveProgressBar()
                        {
                            Value = new BindableProgressBarValue("MediaControl.Position"),
                            ValueStringOverride = MusicDurationConverter.ToTime(music.Duration),
                            Title = "Lyrics To Be Implemented",
                            Status = MusicDurationConverter.ToTime(MediaControl.Position)
                        }
                    }
                }
            },
            Actions = new ToastActionsCustom()
            {
                Buttons =
                {
                    new ToastButton("Pause", "Pause")
                    {
                        ActivationType = ToastActivationType.Background
                    },
                    new ToastButton("Next", "Next")
                    {
                        ActivationType = ToastActivationType.Background
                    }
                },
            },
            Launch = "Launch",
            Audio = Helper.SlientToast,
        };

        // Create the toast notification
        var toast = new ToastNotification(toastContent.GetXml())
        {
            ExpirationTime = DateTime.Now.AddSeconds(music.Duration),
        };
        toast.Activated += Toast_Activated;
        Helper.ShowToast(toast);
    }

    private async void Toast_Activated(ToastNotification sender, object args)
    {
        await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
        {
            switch ((args as ToastActivatedEventArgs).Arguments)
            {
                case "Next":
                    MediaControl.NextMusic();
                    break;
                case "Pause":
                    PauseMusic();
                    break;
                default:
                    break;
            }
        });
    }

I want to send music notifications when my app window is not visible.

My first question is that, the Pause and Next action will trigger some UI changes, which will raise the window of my app. But I don't want it to be raised. What should I do? And how can I prevent my toast from disappearing on activated (in other words, on clicking any part of the toast)?

My second question is, I want to bind the position of a MediaPlayer object to the Value of progressbar, but my notification toast doesn't update its value. How can I keep the value updated? How can I keep the status updated (it is a string that needs to be converted to)?

My last question is, even though I set the expire time to be Music.Duration, which is usually several minutes, why does my toast disappear after a couple of seconds?

Sorry for so many questions. Thanks in advance!


Solution

  • Q1:Activated

    You should choose to perform tasks from the background,so that when you click the button, the app will not be activated.The specific content you can refer to this document.In addition,it is impossible to prevent toast from disappearing on activated when you click it.

    Q2:Update

    You can use toast.Data to bind the progress.The specific steps you can refer to this document.

    new AdaptiveProgressBar()
                            {​
                                Value = new BindableProgressBarValue("progressValue"),​
                                ValueStringOverride = new BindableString("progressValueString"),​
                                Status = new BindableString("progressStatus")​
                            }
    
    string tag = "Myplaylist";
    string group = "playing";​
    toast.Tag = tag;​
    toast.Group = group;​
    toast.Data = new NotificationData();​
    toast.Data.Values["progressValue"] = "0.0";​
    toast.Data.Values["progressValueString"] = "My first song";​
    toast.Data.Values["progressStatus"] = "Playing...";​
    toast.Data.SequenceNumber = 0;
    

    When you want to updata the progress,invoke the following method.

    public void UpdateProgress()
            {​
                // Construct a NotificationData object;​
                string tag = "Myplaylist";​
                string group = "playing";​
    ​
                // Create NotificationData and make sure the sequence number is incremented​
                // since last update, or assign 0 for updating regardless of order​
                var data = new NotificationData​
                {​
                    SequenceNumber = 0​
                };​
    
                data.Values["progressValue"] = "0.7";​
                data.Values["progressValueString"] = "My first song";​
    ​
                // Update the existing notification's data by using tag/group​
                ToastNotificationManager.CreateToastNotifier().Update(data, tag, group);​
            }
    

    Q3:Expire

    The expiration time setting refers to when the message center list clears the message, not the time the toast is kept.The solution is: you can set Scenario = ToastScenario.Reminder in toastContent.The toast will still appear in the screen till clicked.