かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Xamarin.Androidで通知を出す

Notificationを出す最小限のコードは以下の通り。BlankAppを作った時のOnCreateあたりの処理を以下のコードに変えたら動きます。

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);

    // Get our button from the layout resource,
    // and attach an event to it
    Button button = FindViewById<Button>(Resource.Id.MyButton);

    button.Click += (_, __) =>
    {
        var n = new Notification.Builder(this)
            .SetContentTitle("Hello notification")
            .SetSmallIcon(Resource.Drawable.Icon)
            .Build();

        var nm = (NotificationManager)this.GetSystemService(Context.NotificationService);
        nm.Notify(0, n);
    };
}

これで、押しても何も起きない通知が表示されます。

これだけじゃさみしいので押したときにアプリを起動するのをやってみようと思います。NotificationにIntentを渡すことで実現します。Intentの渡し方は、TaskStackBuilderを作って、AddNextIntentメソッドを使ってIntentを設定したあとにGetPendingIntentメソッドを使ってPendingIntentを取得します。取得したPendingIntentをNotification.BuilderのSetContentIntentに設定することで、通知をクリックしたときにIntentが起動されるという感じみたいです。

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);

    // Get our button from the layout resource,
    // and attach an event to it
    Button button = FindViewById<Button>(Resource.Id.MyButton);

    button.Click += (_, __) =>
    {
        var pendingIntent = TaskStackBuilder.Create(this)
            .AddNextIntent(new Intent(this, typeof(MainActivity)))
            .GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);

        var n = new Notification.Builder(this)
            .SetContentTitle("Hello notification")
            .SetSmallIcon(Resource.Drawable.Icon)
            .SetContentIntent(pendingIntent)
            .Build();

        var nm = (NotificationManager)this.GetSystemService(Context.NotificationService);
        nm.Notify(0, n);
    };
}