首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows 8 應用程式開發實戰:磚、推播通知與排程 Toast

     編輯:關於.NET

Windows 8 開始畫面的動態磚是應用程式的重要進入點。本實驗示範:建立次要磚固定特定食譜、使用 Windows Push Notification Service (WNS) 更新主要磚內容、排程 Toast 通知提醒使用者。

練習 1:次要磚固定食譜

  1. 在 ItemDetailPage 應用程式列新增 Pin 按鈕(PinAppBarButtonStyle)。
  2. 點擊時建立 SecondaryTile:
var tile = new SecondaryTile(
    item.UniqueId,           // Tile ID
    item.ShortTitle,         // 短名
    item.Title,              // 顯示名
    item.UniqueId,           // 啟動引數
    TileOptions.ShowNameOnLogo,
    new Uri(item.TileImagePath.AbsoluteUri) // 150x150 本地圖片
);
await tile.RequestCreateAsync();
  1. 在 App.xaml.cs OnLaunched 處理次要磚啟動:
if (!String.IsNullOrEmpty(args.Arguments))
{
    rootFrame.Navigate(typeof(ItemDetailPage), args.Arguments);
    Window.Current.Activate();
    return;
}

練習 2:推播通知更新主要磚

  1. 修改 Package.appxmanifest 封裝名稱/發行者以符合 Azure 測試服務:
Package Name: BUILD.87821274-9e97-488c-b5af-69dace508bff
Publisher: Contoso (需選取 Contoso.pfx 憑證)
  1. 在 OnLaunched 註冊推播通道並訂閱 Azure 服務:
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
var uri = CryptographicBuffer.EncodeToBase64String(
    CryptographicBuffer.ConvertStringToBinary(channel.Uri, BinaryStringEncoding.Utf8));
var client = new HttpClient();
await client.GetAsync($"https://ContosoRecipes8.cloudapp.net?uri={uri}&type=tile");
  1. 服務每 2 分鐘推送一次磚更新 XML,即使應用未執行,開始畫面磚也會輪播最新食譜。

磚更新效果

練習 3:排程 Toast 提醒

  1. 在應用程式列新增 Reminder 按鈕(自訂 ReminderAppBarButtonStyle)。
  2. 點擊建立 30 秒後顯示的 ScheduledToastNotification:
var template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
template.GetElementsByTagName("text")[0].AppendChild(template.CreateTextNode("Reminder!"));
var toast = new ScheduledToastNotification(template, DateTimeOffset.Now.AddSeconds(30));
ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast);
  1. 在 Package.appxmanifest → 應用程式 UI → **支援 Toast 通知** 設為 **是**。

Toast 通知效果

關鍵類別總結

類別用途
SecondaryTile建立次要磚,啟動時帶入引數
PushNotificationChannelManager取得 WNS 通道 URI
TileUpdateManager / BadgeUpdateManager本地更新磚/徽章
ToastNotificationManager建立/排程 Toast
ScheduledToastNotification離線排程 Toast

實務建議

  • 磚圖片必須為本地檔案(ms-appx:/// 或 ms-appdata:///local/),不可遠端 URL。
  • 推播通道 URI 有效期約 30 天,需定期更新(ChannelUriChanged 事件)。
  • Toast 內容遵循 XML 模板,支援圖片、音訊、動作按鈕(ToastText02、ToastImageAndText01 等)。
  • 使用者可在設定中關閉應用程式通知,程式碼應檢查 ToastNotifier.Setting。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved