fc2ブログ

記事一覧

ローカル通知する方法 | Xamarin.Forms


今回はスマホの画面上に通知を表示する(ローカル通知/Local Notification)方法をご紹介いたします。
AndroidとiOSでソースが異なることから、毎度お馴染みDependencyServiceにて記述していきます。
プッシュ通知に関しては以下のURLにてご紹介しております。
https://itblog.dynaspo.com/blog-entry-233.html


Android4
xamarin_notification_android_01.png
iOS9
xamarin_notification_ios_02.png



前提条件
・Windows10
・Visual Studio 2015 Community Update3
・Xamarin 4.3.0.784 (NuGet Xamarin.Forms 2.3.4.224)
・macOS Sierra 10.12.4 / Xcode8.3.1 / Xamarin.iOS 10.4.0.123



1.PCLの記述方法

PCLプロジェクト内にDependencyServiceで呼び出すためのインターフェースを配置します。
INotificationService.cs
//DependencyServiceから利用する
public interface INotificationService
{
//iOS用の登録
void Regist();
    //通知する
    void On(string title, string body);
    //通知を解除する
    void Off();
}



2.Androidの実装方法

Androidプロジェクト内に以下のクラスを配置します。
NotificationService.cs
using Android.App;
using Android.Content;
using Android.Media;
using Xamarin.Forms;
using AppName.Services;
using AppName.Droid.Services;
[assembly: Dependency(typeof(NotificationService))]
public class NotificationService : INotificationService
{
    // 通知のID
    int id = 0;

public void Regist()
{
//iOS用なので、何もしない
}

    public void On(string title, string body)
    {
        Context context = Forms.Context;
        Intent intent = new Intent(context, typeof(MainActivity));
        PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, intent, 0);

//デフォルトの通知音を取得
Android.Net.Uri uri = RingtoneManager.GetDefaultUri(RingtoneType.Notification);

        Notification notification = new Notification.Builder(context)
                .SetContentTitle(title)
                .SetSmallIcon(Resource.Drawable.icon) //ターゲットフレームワークが7.0以降の場合は、動作OSが6.0以降にて透過アイコンを設定してください。
.SetColor(ActivityCompat.GetColor(_context, Resource.Color.notification_color)); //ターゲットフレームワークが7.0以降の場合は、動作OSが6.0以降ではColor.xmlに通知用のカラーを設定してください。
                .SetContentText(body)
                .SetOngoing(false) //常駐するかどうか
                .SetContentIntent(pendingIntent)
.SetSound(uri) //通知音の設定
                .Build();

        NotificationManager manager = (NotificationManager)context.GetSystemService(Context.NotificationService);
        manager.Notify(id, notification);
    }

    public void Off()
    {
        Context context = Forms.Context;
        NotificationManager manager = (NotificationManager)context.GetSystemService(Context.NotificationService);
        manager.Cancel(id);
    }
}


※ターゲットフレームワークが7.0以降の場合は以下の項目を color.xml に追記する必要があります。
Dorid\Resources\values\colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="splash_background">#CCCCCC</color>
</resources>



3.iOSでの実装方法

iOSプロジェクト内に以下のクラスを配置します。
※iOS9までの通知方法となります。iOS10からはソースが異なっており、以下のURLにてご紹介しています。
https://itblog.dynaspo.com/blog-entry-185.html
尚、全てのバージョンに対応するにはUIDevice.CurrentDevice.CheckSystemVersion(10, 0) を使用して分岐が必要です。

NotificationService.cs
using System;
using Foundation;
using UIKit;
using Xamarin.Forms;
using AppName.Services;
using AppName.iOS.Services;
[assembly: Dependency(typeof(NotificationService))]
public class NotificationService : INotificationService
{
    UILocalNotification _notification;

public void Regist()
{
// 許可をもらう通知タイプの種類を定義
UIUserNotificationType types = UIUserNotificationType.Badge | // アイコンバッチ
UIUserNotificationType.Sound | // サウンド
UIUserNotificationType.Alert; // テキスト
// UIUserNotificationSettingsの生成
UIUserNotificationSettings nSettings = UIUserNotificationSettings.GetSettingsForTypes(types, null);
// アプリケーションに登録
UIApplication.SharedApplication.RegisterUserNotificationSettings(nSettings);
}

    public void On(string title, string body)
    {
UIApplication.SharedApplication.InvokeOnMainThread(delegate
{
        _notification = new UILocalNotification();
_notification.Init();
         _notification.FireDate = NSDate.FromTimeIntervalSinceNow(10); //メッセージを通知する日時
        _notification.TimeZone = NSTimeZone.DefaultTimeZone;
//_notification.RepeatInterval = NSCalendarUnit.Day; // 日々繰り返しする場合
         _notification.AlertTitle = title;
        _notification.AlertBody = body;
        _notification.AlertAction = @"Open"; //ダイアログで表示されたときのボタンの文言
         _notification.UserInfo = NSDictionary.FromObjectAndKey(new NSString("NotificationValue"), new NSString("NotificationKey"));
        _notification.SoundName = UILocalNotification.DefaultSoundName;
        // アイコン上に表示するバッジの数値
UIApplication.SharedApplication.ApplicationIconBadgeNumber += 1;
        //通知を登録
        UIApplication.SharedApplication.ScheduleLocalNotification(_notification);
    });
}
    public void Off()
    {
UIApplication.SharedApplication.InvokeOnMainThread(delegate
{
//通知時に設定したUserInfoを元に通知情報をキャンセルする
        if (_notification != null &&
(NSString)(_notification.UserInfo.ObjectForKey(new NSString("NotificationKey"))) == new NSString("NotificationValue"))
{
            UIApplication.SharedApplication.CancelLocalNotification(_notification);
        }
});
    }
}


※iOSでは通知をするためのユーザーの許可設定が必要です。
ユーザーに許可を促すためにRegistのメソッドを予め実行して許可を求めます。

xamarin_notification_ios_01.png



4.使用方法

TestPage.xaml.cs
using AppName.Services;
using Xamarin.Forms;
public partial class TestPage : ContentPage
{
//PCLのXaml.csファイルのコンストラクタ等に記述します。
public TestPage()
{
//通知設定をiOSに登録
DependencyService.Get<INotificationService>().Regist();
}
//PCLのXaml.csファイルの任意の場所で記述します。
void OnNotificationClick(object sender, EventArgs e)
{
//通知を実行
DependencyService.Get<INotificationService>().On(”タイトルテスト”, ”本文テスト”);
}
}



5.iOSの場合の補足

iOSではアプリが画面上で表示されていると通知が表示されません。そこで以下のように記述するとメッセージで表示してくれるようになります。

AppDelegate.cs
public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
{
    //画面に通知を表示するダイアログ
    var alert = new UIAlertView();
    alert.Title = notification.AlertTitle;
    alert.Message = notification.AlertBody;
    alert.AddButton(notification.AlertAction);
    alert.Show();
}

<注意点>
尚、Appleの仕様として、ローカル通知はアプリ毎に64件までしか登録ができないようです。それ以上の通知登録については破棄されているようです。
また、iOSではBackground Fetchバックグラウンドタスクの2種類のバックグラウンド処理がありますが、バックグラウンド処理からローカル通知を呼び出す場合はInvokeOnMainThread内に記述する必要があります。詳しくは以下のURLをご参考ください。
https://itblog.dynaspo.com/blog-entry-173.html



6.通知に画像を表示するには

通知情報にアイコン以外の画像を表示する方法を以下の記事にてご紹介しています。
Androidの場合はこちら
iOSの場合はこちら



7.通知にアクションボタンを表示するには

通知情報にボタンを表示し、その選択結果をプログラムで取得する方法は以下の記事にてご紹介しています。
Androidの場合はこちら
iOSの場合はこちら



8.追記

Android 8 Oreo 以降の通知の実装方法




最後までお読みいただきありがとうございます。
当ブログの内容をまとめた Xamarin逆引きメニュー は以下のURLからご覧になれます。
https://itblog.dynaspo.com/blog-entry-81.html


関連記事

コメント

コメントの投稿

※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。

 入力されていないコメントには返信しませんのであらかじめご了承くださいませ。

※ニックネームでも良いので必ずご入力ください。

    

※必ずご入力ください。

    
    

※必ずご入力ください。

※技術的な質問には環境やエラーについて正確かつ詳細にお教えください。

・正確なエラーの内容

・Windowsのバージョン番号

・Visual Studioのバージョン

・機器の型番

・アプリやソフトのバージョン

    

カテゴリ別記事一覧

広告

プロフィール

石河 純


著者名 :石河 純
自己紹介:素人上がりのIT技術者。趣味は卓球・車・ボウリング

IT関連の知識はざっくりとこんな感じです。
【OS関連】
WindowsServer: 2012/2008R2/2003/2000/NT4
Windows: 10/8/7/XP/2000/me/NT4/98
Linux: CentOS RedHatLinux9
Mac: macOS Catalina 10.15 / Mojave 10.14 / High Sierra 10.13 / Sierra 10.12 / OSX Lion 10.7.5 / OSX Snow Leopard 10.6.8
【言語】
VB.net ASP.NET C#.net Java VBA
Xamarin.Forms
【データベース】
Oracle 10g/9i
SQLServer 2016/2008R2/2005/2000
SQLAnywhere 16/11/8
【BI/レポートツール】
Cognos ReportNet (IBM)
Microsoft PowerBI
ActiveReport (GrapeCity)
CrystalReport
【OCX関連】
GrapeCity InputMan SPREAD MultiRow GridView
【ネットワーク関連】
CCNP シスコ技術者認定
Cisco Catalyst シリーズ
Yamaha RTXシリーズ
FireWall関連
【WEB関連】
SEO SEM CSS jQuery IIS6/7 apache2

休みの日は卓球をやっています。
現在、卓球用品通販ショップは休業中です。