UWP アプリでアプリ通知を使用する

アプリ通知は、アプリのウィンドウの外側に表示される UI ポップアップで、タイムリーな情報やアクションをユーザーに提供します。 通知は、純粋に情報に関する情報である場合や、クリックされたときにアプリを起動したり、アプリをフォアグラウンドに移動せずにバックグラウンド アクションをトリガーしたりできます。

アプリ通知のスクリーンショット

この記事では、UWP アプリからアプリ通知を作成して送信し、ユーザーが操作するときにアクティブ化を処理する手順について説明します。

アプリ通知の概要と他のフレームワークのガイダンスについては、「 アプリ通知の概要」を参照してください。

この記事では、ローカル通知について説明します。 クラウド サービスからの通知の配信については、「 プッシュ通知の概要」を参照してください。

前提条件

  • Visual Studioの UWP アプリ プロジェクト
  • ユニバーサル Windows プラットフォーム開発ワークロードがVisual Studioにインストールされている

アプリ通知を送信する

UWP アプリでは、Windows.UI.Notifications 名前空間を使用して、XML を使用して通知を作成および送信します。 このセクションでは、C# と C++ を使用して通知を送信する方法について説明します。

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

var xml = @"<toast launch=""action=viewConversation&amp;conversationId=9813"">
    <visual>
        <binding template=""ToastGeneric"">
            <text>Andrew sent you a picture</text>
            <text>Check this out, The Enchantments in Washington!</text>
        </binding>
    </visual>
</toast>";

var doc = new XmlDocument();
doc.LoadXml(xml);

var notification = new ToastNotification(doc);
ToastNotificationManager.CreateToastNotifier().Show(notification);

アクティブ化を処理する

ユーザーが通知をクリックすると (またはフォアグラウンドアクティブ化を使用した通知のボタン)、アプリの OnActivated メソッドが呼び出されます。 OnLaunchedは、アプリが閉じられ、初めて起動される場合でも、通知のアクティブ化には呼び出されません。 共有初期化メソッドに OnLaunchedOnActivated を組み合わせることをお勧めします。

App.xaml.cs

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    OnLaunchedOrActivated(e.PreviousExecutionState);

    var rootFrame = Window.Current.Content as Frame;
    if (e.PrelaunchActivated == false)
    {
        if (rootFrame?.Content == null)
        {
            rootFrame?.Navigate(typeof(MainPage), e.Arguments);
        }
        Window.Current.Activate();
    }
}

protected override void OnActivated(IActivatedEventArgs e)
{
    OnLaunchedOrActivated(e.PreviousExecutionState);

    if (e is ToastNotificationActivatedEventArgs toastArgs)
    {
        var rootFrame = Window.Current.Content as Frame;
        if (rootFrame?.Content == null)
        {
            rootFrame?.Navigate(typeof(MainPage));
        }
        Window.Current.Activate();

        // Parse the notification arguments
        string argument = toastArgs.Argument;
        // TODO: Navigate to the relevant content based on the arguments
    }
}

private void OnLaunchedOrActivated(ApplicationExecutionState previousState)
{
    if (Window.Current.Content is not Frame)
    {
        var rootFrame = new Frame();
        rootFrame.NavigationFailed += OnNavigationFailed;
        Window.Current.Content = rootFrame;
    }
}

ボタン、画像、入力、オーディオ、その他のリッチ コンテンツを通知に追加する方法については、「 アプリ通知コンテンツ」を参照してください。