35、ScheduledNotifications

 

位于 Windows.UI.Notifications 命名空间的更新通知的类 :

namespace Windows.UI.Notifications
{    
    //向通知程序绑定到的特定应用程序引发消息通知。此类还允许您计划并移除消息通知。
     public sealed class ToastNotifier
    {
        // 获取一个值,该值告知您是否有阻止显示 Toast 通知的应用程序、用户或系统块。       
         // 返回结果: Enabled 如果消息可以显示;否则,一个或多个原因将使消息被阻止。
        public NotificationSetting Setting { get; }

       //Windows 添加 ScheduledToastNotification 以便稍后显示。
        // 参数: scheduledToast:
       // 包括其内容和计时说明的计划消息通知。
        public void AddToSchedule(ScheduledToastNotification scheduledToast);
       
       // 获取该应用程序计划显示的 ScheduledToastNotification 对象的集合。      
        // 返回结果:  应用程序已绑定到此通知程序的计划消息通知的集合已针对限时显示进行计划。
        public IReadOnlyList<ScheduledToastNotification> GetScheduledToastNotifications();
       
       //  删除屏幕中的指定消息通知。       
        // notification:  指定要隐藏的消息的对象。
        public void Hide(ToastNotification notification);
      
       //  取消指定 ScheduledToastNotification 的计划显示。        
        // scheduledToast:  从计划中移除的通知。
        public void RemoveFromSchedule(ScheduledToastNotification scheduledToast);
       
       // 显示指定的消息通知。
        //notification: 包含要显示的消息通知内容的对象。
        public void Show(ToastNotification notification);
    }

 

namespace Windows.UI.Notifications
{
   
    //更改更新程序绑定到的特定图块的内容。
    public sealed class TileUpdater
    {
       // 获取一个值,该值指定是否应通过通知来更新图块。
        // 返回结果: 指示图块可通过通知更新或者禁用通知的人员(开发人员、用户或管理员)的值。
        public NotificationSetting Setting { get; }
      
       // 向计划添加 ScheduledTileNotification。
        //scheduledTile:  计划平铺更新对象。
        public void AddToSchedule(ScheduledTileNotification scheduledTile);
      
       // 删除所有更新并将平铺还原为其默认内容(如应用程序清单所声明)。
        public void Clear();
      
       // 使图块能够排列最多五个通知。
        //enable:  如果启用排队,则为 True;否则为 false。
        public void EnableNotificationQueue(bool enable);
       
       // 将计划更新列表检索到图块。
        // 返回结果: 此图块的计划更新的集合。
        public IReadOnlyList<ScheduledTileNotification> GetScheduledTileNotifications();
      
       // 删除计划中即将到来的平铺更新。      
        // scheduledTile: 从计划中移除的通知。
        public void RemoveFromSchedule(ScheduledTileNotification scheduledTile);
      
        public void StartPeriodicUpdate(Uri tileContent, PeriodicUpdateRecurrence requestedInterval);
       
        public void StartPeriodicUpdate(Uri tileContent, DateTimeOffset startTime, PeriodicUpdateRecurrence requestedInterval);
       
        public void StartPeriodicUpdateBatch(IEnumerable<Uri> tileContents, PeriodicUpdateRecurrence requestedInterval);
      
        public void StartPeriodicUpdateBatch(IEnumerable<Uri> tileContents, 
DateTimeOffset startTime, PeriodicUpdateRecurrence requestedInterval);
//为更新程序绑定的图块取消当前系列的计时更新。 public void StopPeriodicUpdate(); // 将内容或外观的更改应用于图块。 // notification: 为平铺的内容提供新的 XML 定义的对象。 public void Update(TileNotification notification); } }

 

 

 

  1、Scheduling a toast or tile update:

    Tiles 和 Toasts 通知可以在指定的时间内进行更新。Toasts 通知也可以指定在一定间隔内重复显示。这些通知

可以在应用没有运行的情况下显示。

操作截图:

 

当 RadioButton 选中 Toast 时,在屏幕右上角显示 Toast 通知的结果:

 

当 RadioButton 选中 Tile 时,在开始菜单上显示 Tile 通知为 :

 

页面的 xaml :

//设定在多长时间后显示
 <TextBox x:Name="FutureTimeBox" Width="60" Text="3" MaxLength="3" />

//显示 Toast 通知,还是 Tile 通知,默认选择Toast 
<RadioButton GroupName="Type" x:Name="ToastRadio" IsChecked="true" Content="Toast"/>
<RadioButton GroupName="Type" Content="Tile"/>

//显示在通知中的文字
 <TextBox x:Name="StringBox" Width="200" MaxLength="50" />

//使用 NotificationsExtensions 扩展库显示
<Button x:Name="ScheduleButton" Content="Schedule Notification" Click="ScheduleButton_Click"/>

//使用自定义 xml 字符串显示
<Button x:Name="ScheduleButtonString" Content="Schedule Notification" Click="ScheduleButton_Click"/>

 

相应的 C# :

        void ScheduleButton_Click(Object sender, RoutedEventArgs e)
        {
           //为 false 时是 StringBox 按钮触发, 为 true 时是 ScheduleButtonString 按钮触发
             bool useStrings = false;
            if (sender == ScheduleButtonString)
            {
                useStrings = true;
            }

            try
            {
                Int16 dueTimeInSeconds = Int16.Parse(FutureTimeBox.Text);
                if (dueTimeInSeconds <= 0) throw new ArgumentException();

                String updateString = StringBox.Text;
                DateTime dueTime = DateTime.Now.AddSeconds(dueTimeInSeconds);

                Random rand = new Random();
                //随机产生一个 id
                int idNumber = rand.Next(0, 10000000);

                if (ToastRadio.IsChecked != null && (bool)ToastRadio.IsChecked)
                {
                    if (useStrings)
                    {
                      //使用自定义 xml 字符串显示
                         ScheduleToastWithStringManipulation(updateString, dueTime, idNumber);
                    }
                    else
                    {
                       //使用 NotificationsExtensions 扩展库显示
                          ScheduleToast(updateString, dueTime, idNumber);
                    }
                }
                else
                {
                    if (useStrings)
                    {
                       //使用自定义 xml 字符串显示
                          ScheduleTileWithStringManipulation(updateString, dueTime, idNumber);
                    }
                    else
                    {
                       //使用 NotificationsExtensions 扩展库显示
                         ScheduleTile(updateString, dueTime, idNumber);
                    }
                }
            }
            catch (Exception)
            {
                //你必须输入一个有效的时间(秒)
            }
        }

 

Toast 通知, 使用了 NotificationsExtensions 扩展库:

void ScheduleToast(String updateString, DateTime dueTime, int idNumber)
        {
            // 其它类型的 toast 通知也是使用类似的设置
             IToastText02 toastContent = ToastContentFactory.CreateToastText02();
            toastContent.TextHeading.Text = updateString;
            toastContent.TextBodyWrap.Text = "Received: " + dueTime.ToLocalTime();

            ScheduledToastNotification toast;

           //是否是循环显示通知
             if (RepeatBox.IsChecked != null && (bool)RepeatBox.IsChecked)
            {
                toast = new ScheduledToastNotification(toastContent.GetXml(), dueTime, TimeSpan.FromSeconds(60), 5);

              // 您可以指定一个ID,以便在之后管理该 toast 通知。
                // 确保ID是少于或等于 15 个字符。
                toast.Id = "Repeat" + idNumber;
            }
            else
            {
                toast = new ScheduledToastNotification(toastContent.GetXml(), dueTime);
                toast.Id = "Toast" + idNumber;
            }

            // CreateToastNotifier() : 创建并初始化绑定到调用应用程序的 ToastNotification 
            //的新实例,此操作可让您引发对该应用程序的消息通知。
            //AddToSchedule() :  Windows 添加 ScheduledToastNotification 以便稍后显示。
             ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
          
        }


Toast 通知, 使用自定义的 xml 字符串显示:

void ScheduleToastWithStringManipulation(String updateString, DateTime dueTime, int idNumber)
        {
            // 其它类型的 toast 通知也是使用类似的设置
            string toastXmlString = "<toast>"
            + "<visual>"
            + "<binding template='ToastText02'>"
            + "<text id='2'>" + updateString + "</text>"
            + "<text id='1'>" + "Received: " + dueTime.ToLocalTime() + "</text>"
            + "</binding>"
            + "</visual>"
            + "</toast>";

            Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
            try
            {
                //使用所提供的字符串加载 XML 文档。使用默认分析器设置分析文件。
                  toastDOM.LoadXml(toastXmlString);

                ScheduledToastNotification toast;
                if (RepeatBox.IsChecked != null && (bool)RepeatBox.IsChecked)
                {
                    toast = new ScheduledToastNotification(toastDOM, dueTime, TimeSpan.FromSeconds(60), 5);
   
// 您可以指定一个ID,以便在之后管理该 toast 通知。

               
// 确保ID是少于或等于 15 个字符。 toast.Id
= "Repeat" + idNumber; } else { toast = new ScheduledToastNotification(toastDOM, dueTime); toast.Id = "Toast" + idNumber; } ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast); } catch (Exception) { //加载 xml 错误 } }

 

 

 

Tile 通知, 使用 NotificationsExtensions 扩展库:

     void ScheduleTile(String updateString, DateTime dueTime, int idNumber)
        {
            // 设置显示的文本
              ITileWideText09 tileContent = TileContentFactory.CreateTileWideText09();
            tileContent.TextHeading.Text = updateString;
            tileContent.TextBodyWrap.Text = "Received: " + dueTime.ToLocalTime();

            // 设置相应的方形 Tile 的文本
              ITileSquareText04 squareContent = TileContentFactory.CreateTileSquareText04();
            squareContent.TextBodyWrap.Text = updateString;

            tileContent.SquareContent = squareContent;

            // 创建一个 notification  对象
             ScheduledTileNotification futureTile = new ScheduledTileNotification(tileContent.GetXml(), dueTime);
            futureTile.Id = "Tile" + idNumber;

            //添加到计划le
            // 你可以使用  CreateTileUpdaterForSecondaryTile(tileId) 方法,
            //根据同样的方式更新一个次级 tile
            // 创建并初始化 TileUpdater 的新实例,此操作可让您更改调用应用程
            //序图块的外观。然后,向计划添加 ScheduledTileNotification。
            TileUpdateManager.CreateTileUpdaterForApplication().AddToSchedule(futureTile);
          
        }

 

Tile 通知,使用 自定义的 xml 字符串:

 

 void ScheduleTileWithStringManipulation(String updateString, DateTime dueTime, int idNumber)
        {
            string tileXmlString = "<tile>"
                         + "<visual>"
                         + "<binding template='TileWideText09'>"
                         + "<text id='1'>" + updateString + "</text>"
                         + "<text id='2'>" + "Received: " + dueTime.ToLocalTime() + "</text>"
                         + "</binding>"
                         + "<binding template='TileSquareText04'>"
                         + "<text id='1'>" + updateString + "</text>"
                         + "</binding>"
                         + "</visual>"
                         + "</tile>";

            Windows.Data.Xml.Dom.XmlDocument tileDOM = new Windows.Data.Xml.Dom.XmlDocument();
            try
            {
                tileDOM.LoadXml(tileXmlString);

                // 创建一个 notification  对象
                  ScheduledTileNotification futureTile = new ScheduledTileNotification(tileDOM, dueTime);
                futureTile.Id = "Tile" + idNumber;

               // 添加到计划中
                 //你可以使用  CreateTileUpdaterForSecondaryTile(tileId) 方法,根据同
               //样的方式更新一个次级 tile                
TileUpdateManager.CreateTileUpdaterForApplication().AddToSchedule(futureTile) } catch (Exception) { //加载 xml 错误 } }

 

 

2、Querying and removing notifications:

      在之前给应用设置的通知都可以获得, 并且可以删除。

  操作: 在 1、中分别添加一个 Tile 通知 和 Toast 通知,然后可以获得并显示:

 

页面中的 xaml :

Page 的资源:

<Page.Resources>
    <Style x:Key="ItemTitleStyle" TargetType="TextBlock">
      <Setter Property="FontFamily" Value="Segoe UI Light"/>
      <Setter Property="Foreground" Value="Black"/>
      <Setter Property="FontSize" Value="16"/>
      <Setter Property="FontWeight" Value="Bold"/>
    </Style>

    <Style x:Key="ItemLineStyle" TargetType="TextBlock">
      <Setter Property="FontFamily" Value="Segoe UI Light"/>
      <Setter Property="Foreground" Value="Black"/>
      <Setter Property="FontSize" Value="14"/>
    </Style>

    <DataTemplate x:Key="TileTemplate">
      <Border BorderThickness="2" BorderBrush="Red" Width="338" Height="88">
        <StackPanel Orientation="Vertical" Margin="10,10,0,0">
          <TextBlock Style="{StaticResource ItemTitleStyle}" Text="{Binding ItemType}" />
          <TextBlock Style="{StaticResource ItemLineStyle}">
            ID: <Run Text="{Binding ItemId}" />
          </TextBlock>
          <TextBlock Style="{StaticResource ItemLineStyle}">
            String: <Run Text="{Binding InputString}" />
          </TextBlock>
          <TextBlock Style="{StaticResource ItemLineStyle}">
            Due time: <Run Text="{Binding DueTime}" />
          </TextBlock>
        </StackPanel>
      </Border>
    </DataTemplate>

    <Style x:Key="TileStyle" TargetType="GridViewItem">
      <Setter Property="FontFamily" Value="Segoe UI" />
      <Setter Property="Foreground" Value="White" />
      <Setter Property="Height" Value="100" />
      <Setter Property="Width" Value="350" />
      <Setter Property="Padding" Value="0" />
      <Setter Property="Margin" Value="5" />
      <Setter Property="HorizontalContentAlignment" Value="Left" />
      <Setter Property="VerticalContentAlignment" Value="Top" />
    </Style>

    <ItemsPanelTemplate x:Key="ItemsPanelTemplate">
      <WrapGrid MaximumRowsOrColumns="3" VerticalChildrenAlignment="Top" HorizontalChildrenAlignment="Left" Margin="0,0,0,0"/>
    </ItemsPanelTemplate>
  </Page.Resources>

 

//显示应用之前定义的 Tile 和 Toast 通知
<GridView x:Name="ItemGridView" Width="Auto" MaxWidth="700" MinHeight="325" Height="Auto"
      ItemTemplate="{StaticResource TileTemplate}"
      ItemContainerStyle="{StaticResource TileStyle}"
      ItemsPanel="{StaticResource ItemsPanelTemplate}"
      SelectionMode="Multiple"
      BorderBrush="Blue"
      BorderThickness="2"
      VerticalAlignment="Stretch"
      ScrollViewer.VerticalScrollBarVisibility="Auto"
      ScrollViewer.HorizontalScrollBarVisibility="Auto"/>

//删除通知按钮
<Button x:Name="RemoveButton" Content="Remove selected notifications from schedule" Margin="0,0,10,0"/>

//刷新 GridView 列表
<Button x:Name="RefreshListButton" Content="Refresh List" Margin="0,0,10,0"/>

 

相应的 C# :

首先定义显示通知的 类 :

internal class NotificationData
{
    public String ItemType { get; set; }
    public String ItemId { get; set; }
    public String DueTime { get; set; }
    public String InputString { get; set; }
    public Boolean IsTile { get; set; }
}

 

在页面的 OnNavigatedTo() 方法中调用 RefreshListView()  方法,获取已经定义的通知,并且绑定到 GridView 上面:

 protected override void OnNavigatedTo(NavigationEventArgs e)
 {   
     RefreshListView();
 }

 

void RefreshListView()
        {

           // 获取该应用程序计划显示的 ScheduledToastNotification 对象的集合。
           //返回结果 : 应用程序已绑定到此通知程序的计划消息通知的集合已针对限时显示进行计划。
            IReadOnlyList<ScheduledToastNotification> scheduledToasts = 
ToastNotificationManager.CreateToastNotifier().GetScheduledToastNotifications();
// 将计划更新列表检索到图块。返回结果: 此图块的计划更新的集合。 IReadOnlyList<ScheduledTileNotification> scheduledTiles =
TileUpdateManager.CreateTileUpdaterForApplication().GetScheduledTileNotifications();
int toastLength = scheduledToasts.Count; int tileLength = scheduledTiles.Count; List<NotificationData> bindingList = new List<NotificationData>(toastLength + tileLength); for (int i = 0; i < toastLength; i++) { ScheduledToastNotification toast = scheduledToasts[i]; bindingList.Add(new NotificationData() { ItemType = "Toast", ItemId = toast.Id,// Toast 通知的 ID DueTime = toast.DeliveryTime.ToLocalTime().ToString(), InputString = toast.Content.GetElementsByTagName("text")[0].InnerText, IsTile = false }); } for (int i = 0; i < tileLength; i++) { ScheduledTileNotification tile = scheduledTiles[i]; bindingList.Add(new NotificationData() { ItemType = "Tile", ItemId = tile.Id, //Tile 通知的 ID
DueTime
= tile.DeliveryTime.ToLocalTime().ToString(), InputString = tile.Content.GetElementsByTagName("text")[0].InnerText, IsTile = false }); } //将检索到的 Toast 通知和 Tile 通知绑定到 GridView 列表上
ItemGridView.ItemsSource = bindingList; }

 

 
//通过检索 GridView 列表中选择的项,在根据它的 ID 进行操作。为每
//个通知指定一个唯一的 ID 很重要,便于管理。你可以把通知的 ID 放
//到本地的存储里面
void Remove_Click(object sender, RoutedEventArgs e)
        {
            IList<Object> items = ItemGridView.SelectedItems;
            for (int i = 0; i < items.Count; i++)
            {
                NotificationData item = (NotificationData)items[i];
                String itemId = item.ItemId;
                if (item.IsTile)
                {

                 // 创建并初始化 TileUpdater 的新实例,此操作可让您更改调用应用程序图块的外观。
                    TileUpdater updater = TileUpdateManager.CreateTileUpdaterForApplication();

                  // 将计划更新列表检索到图块。
                    IReadOnlyList<ScheduledTileNotification> scheduled = updater.GetScheduledTileNotifications();
                    for (int j = 0; j < scheduled.Count; j++)
                    {
                       //如果列表中的 ID 和应用设置在系统中通知的 ID 相同
                          if (scheduled[j].Id == itemId)
                        {
                            // 删除计划中即将到来的平铺更新。
                                updater.RemoveFromSchedule(scheduled[j]);
                        }
                    }
                }
                else
                {
                    //创建并初始化绑定到调用应用程序的 ToastNotification 的新实例,此操作可让您引发对该应用程序的消息通知。
                       ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();
                    IReadOnlyList<ScheduledToastNotification> scheduled = notifier.GetScheduledToastNotifications();
                    for (int j = 0; j < scheduled.Count; j++)
                    {
                        if (scheduled[j].Id == itemId)
                        {

                           // 取消指定 ScheduledToastNotification 的计划显示。        
notifier.RemoveFromSchedule(scheduled[j]); } } } } //删除完成后,刷新列表
RefreshListView(); }

 

posted @ 2012-10-11 16:38  博琼  阅读(659)  评论(1)    收藏  举报