傳送本機磚通知Send a local tile notification

Windows 10 中的主要應用程式磚定義在您的應用程式資訊清單中,次要磚則是以程式設計方式建立,而且是由您的應用程式程式碼定義。Primary app tiles in Windows 10 are defined in your app manifest, while secondary tiles are programmatically created and defined by your app code. 本文說明如何使用彈性磚範本,將本機磚通知傳送到主要磚和次要磚。This article describes how to send a local tile notification to a primary tile and a secondary tile using adaptive tile templates. (本機通知是透過應用程式程式碼傳送,而不是從 Web 伺服器推送或提取)。(A local notification is one that's sent from app code as opposed to one that's pushed or pulled from a web server.)

預設磚和含有通知的磚

 

安裝 NuGet 封裝Install the NuGet package

我們建議您安裝 Notifications 程式庫 NuGet 套件,以物件 (而非原始 XML) 來產生磚承載,讓事情較為簡化。We recommend installing the Notifications library NuGet package, which simplifies things by generating tile payloads with objects instead of raw XML.

此文章中的內嵌程式碼範例適用於使用 Notifications 程式庫的 C#。The inline code examples in this article are for C# using the Notifications library. (如果您想要建立您自己的 XML,您可以在文章後面找到不含 Notifications 程式庫的程式碼範例。)(If you'd prefer to create your own XML, you can find code examples without the Notifications library toward the end of the article.)

新增命名空間宣告Add namespace declarations

若要存取磚 API,請包含 Windows.UI.Notifications 命名空間。To access the tile APIs, include the Windows.UI.Notifications namespace. 我們也建議您包含 Microsoft.Toolkit.Uwp.Notifications 命名空間,這樣您就能利用我們的磚協助程式 API (您必須安裝 Notifications 程式庫 NuGet 套件才能存取這些 API)。We also recommend including the Microsoft.Toolkit.Uwp.Notifications namespace so that you can take advantage of our tile helper APIs (you must install the Notifications library NuGet package to access these APIs).

using Windows.UI.Notifications;
using Microsoft.Toolkit.Uwp.Notifications; // Notifications library

建立通知內容Create the notification content

在 Windows 10 中,磚承載是彈性磚範本定義的,可讓您為您的通知建立自訂的視覺配置。In Windows 10, tile payloads are defined using adaptive tile templates, which allow you to create custom visual layouts for your notifications. (若要深入了解彈性磚可以做什麼,請參閱建立彈性磚。)(To learn what's possible with adaptive tiles, see Create adaptive tiles.)

這個程式碼範例會建立中型和寬形磚的彈性磚內容。This code example creates adaptive tile content for medium and wide tiles.

// In a real app, these would be initialized with actual data
string from = "Jennifer Parker";
string subject = "Photos from our trip";
string body = "Check out these awesome photos I took while in New Zealand!";
 
 
// Construct the tile content
TileContent content = new TileContent()
{
    Visual = new TileVisual()
    {
        TileMedium = new TileBinding()
        {
            Content = new TileBindingContentAdaptive()
            {
                Children =
                {
                    new AdaptiveText()
                    {
                        Text = from
                    },

                    new AdaptiveText()
                    {
                        Text = subject,
                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                    },

                    new AdaptiveText()
                    {
                        Text = body,
                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                    }
                }
            }
        },

        TileWide = new TileBinding()
        {
            Content = new TileBindingContentAdaptive()
            {
                Children =
                {
                    new AdaptiveText()
                    {
                        Text = from,
                        HintStyle = AdaptiveTextStyle.Subtitle
                    },

                    new AdaptiveText()
                    {
                        Text = subject,
                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                    },

                    new AdaptiveText()
                    {
                        Text = body,
                        HintStyle = AdaptiveTextStyle.CaptionSubtle
                    }
                }
            }
        }
    }
};

通知內容在中型磚上顯示時看起來就像下面這樣:The notification content looks like the following when displayed on a medium tile:

中型磚上的通知內容

建立通知Create the notification

擁有通知內容後,您需要建立一個新的 TileNotificationOnce you have your notification content, you'll need to create a new TileNotification. TileNotification 建構函式採用 Windows 執行階段 XmlDocument 物件,如果您使用 Notifications 程式庫,即可透過 TileContent.GetXml 方法取得。The TileNotification constructor takes a Windows Runtime XmlDocument object, which you can obtain from the TileContent.GetXml method if you're using the Notifications library.

這個程式碼範例會為新的磚建立通知。This code example creates a notification for a new tile.

// Create the tile notification
var notification = new TileNotification(content.GetXml());

設定通知的到期時間 (選擇性)Set an expiration time for the notification (optional)

根據預設,本機磚和徽章通知不會到期,而推播、定期以及排程通知則會在三天後到期。By default, local tile and badge notifications don't expire, while push, periodic, and scheduled notifications expire after three days. 磚內容持續的時間不應太長,最佳做法是設定適合您的應用程式的到期時間,特別是針對本機磚和徽章通知。Because tile content shouldn't persist longer than necessary, it's a best practice to set an expiration time that makes sense for your app, especially on local tile and badge notifications.

這個程式碼範例會建立一個到期的通知,而它會在 10 分鐘後移除。This code example creates a notification that expires and will be removed from the tile after ten minutes.

tileNotification.ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(10);

傳送通知Send the notification

雖然在本機傳送磚通知很簡單,但傳送通知到主要或次要磚則稍有不同。Although locally sending a tile notification is simple, sending the notification to a primary or secondary tile is a bit different.

主要磚Primary tile

若要將通知傳送到主要磚,請使用 TileUpdateManager 為主要磚建立磚更新程式,並呼叫 "Update" 來傳送通知。To send a notification to a primary tile, use the TileUpdateManager to create a tile updater for the primary tile, and send the notification by calling "Update". 無論是否可見,您的應用程式主要磚一律會存在,因此即使未釘選它,也可以傳送通知給它。Regardless of whether it's visible, your app's primary tile always exists, so you can send notifications to it even when it's not pinned. 如果使用者之後釘選您的主要磚,屆時就會顯示您傳送的通知。If the user pins your primary tile later, the notifications that you sent will appear then.

這個程式碼範例會傳送通知到主要磚。This code example sends a notification to a primary tile.

// Send the notification to the primary tile
TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);

次要磚Secondary tile

若要傳送通知到次要磚,請先確定次要磚已經存在。To send a notification to a secondary tile, first make sure that the secondary tile exists. 如果您嘗試為不存在的次要磚建立磚更新程式 (例如,如果使用者取消釘選次要磚) ,就會擲回例外狀況。If you try to create a tile updater for a secondary tile that doesn't exist (for example, if the user unpinned the secondary tile), an exception will be thrown. 您可以使用 SecondaryTile.Exists(tileId) 探索您的次要磚是否已釘選,然後再為次要磚建立磚更新程式並傳送通知。You can use SecondaryTile.Exists(tileId) to discover if your secondary tile is pinned, and then create a tile updater for the secondary tile and send the notification.

這個程式碼範例會傳送通知到次要磚。This code example sends a notification to a secondary tile.

// If the secondary tile is pinned
if (SecondaryTile.Exists("MySecondaryTile"))
{
    // Get its updater
    var updater = TileUpdateManager.CreateTileUpdaterForSecondaryTile("MySecondaryTile");
 
    // And send the notification
    updater.Update(notification);
}

預設磚和含有通知的磚

清除磚上的通知 (選擇性)Clear notifications on the tile (optional)

在大部分情況下,在使用者與通知內容互動後就該清除通知。In most cases, you should clear a notification once the user has interacted with that content. 例如,使用者啟動您的應用程式後,您可能要清除磚的所有通知。For example, when the user launches your app, you might want to clear all the notifications from the tile. 如果通知有時間限制,建議您設定通知的到期時間,而不是明確清除通知。If your notifications are time-bound, we recommend that you set an expiration time on the notification instead of explicitly clearing the notification.

這個程式碼範例會清除主要磚的磚通知。This code example clears the tile notification for the primary tile. 您可以建立次要磚的磚更新程式,以針對次要磚達到同樣的目的。You can do the same for secondary tiles by creating a tile updater for the secondary tile.

TileUpdateManager.CreateTileUpdaterForApplication().Clear();

對於啟用了通知佇列的磚以及佇列中的通知,請呼叫 Clear 方法清除佇列。For a tile with the notification queue enabled and notifications in the queue, calling the Clear method empties the queue. 不過,您無法透過您的應用程式伺服器清除通知;只有本機應用程式程式碼才可以清除通知。You can't, however, clear a notification via your app's server; only the local app code can clear notifications.

定期或推播通知只能新增通知或取代現有的通知。Periodic or push notifications can only add new notifications or replace existing notifications. 不論通知本身的來源是推播、定期或本機,本機呼叫 Clear 方法將會清除磚。A local call to the Clear method will clear the tile whether or not the notifications themselves came via push, periodic, or local. 這個方法不會清除尚未顯示的排程通知。Scheduled notifications that haven't yet appeared are not cleared by this method.

含有通知的磚與清除後的磚

後續步驟Next steps

使用通知佇列Using the notification queue

您已經完成第一次的磚更新,現在可以透過啟用通知佇列來擴充磚的功能。Now that you have done your first tile update, you can expand the functionality of the tile by enabling a notification queue.

其他通知傳遞方法Other notification delivery methods

本文說明如何以通知傳送磚更新。This article shows you how to send the tile update as a notification. 若要探索其他通知傳遞方法,包括排程、定期及推播,請參閱傳遞通知To explore other methods of notification delivery, including scheduled, periodic, and push, see Delivering notifications.

XmlEncode 傳遞方法XmlEncode delivery method

如果您不是使用 Notifications 程式庫,這個通知傳遞方法是另一個替代方案。If you're not using the Notifications library, this notification delivery method is another alternative.

public string XmlEncode(string text)
{
    StringBuilder builder = new StringBuilder();
    using (var writer = XmlWriter.Create(builder))
    {
        writer.WriteString(text);
    }

    return builder.ToString();
}

不含 Notifications 程式庫的程式碼範例Code examples without Notifications library

如果您偏好使用原始的 XML 而非 Notifications 程式庫 NuGet 套件,請將這些替代程式碼範例運用到本文的前三個範例。If you prefer to work with raw XML instead of the Notifications library NuGet package, use these alternate code examples to first three examples provided in this article. 其餘的程式碼範例則可搭配 Notifications 程式庫或原始 XML 使用。The rest of the code examples can be used either with the Notifications library or with raw XML.

新增命名空間宣告Add namespace declarations

using Windows.UI.Notifications;
using Windows.Data.Xml.Dom;

建立通知內容Create the notification content

// In a real app, these would be initialized with actual data
string from = "Jennifer Parker";
string subject = "Photos from our trip";
string body = "Check out these awesome photos I took while in New Zealand!";
 
 
// TODO - all values need to be XML escaped
 
 
// Construct the tile content as a string
string content = $@"
<tile>
    <visual>
 
        <binding template='TileMedium'>
            <text>{from}</text>
            <text hint-style='captionSubtle'>{subject}</text>
            <text hint-style='captionSubtle'>{body}</text>
        </binding>
 
        <binding template='TileWide'>
            <text hint-style='subtitle'>{from}</text>
            <text hint-style='captionSubtle'>{subject}</text>
            <text hint-style='captionSubtle'>{body}</text>
        </binding>
 
    </visual>
</tile>";

建立通知Create the notification

// Load the string into an XmlDocument
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
 
// Then create the tile notification
var notification = new TileNotification(doc);