この記事でのバージョン
Unity 2021.3.4f1
Mobile Notifications 2.0.2
はじめに
今回はiOSやAndroidのスマホ端末でサーバーを介さないプッシュの通知、
いわゆるローカルプッシュ通知をUnityで実装する方法の紹介です!
Mobile Notificationsの導入と準備
今回はUnity公式の無料パッケージ、Mobile Notificationsを使います。
導入はおなじみPackageManagerを使います。
上部メニューのWindow/Package Managerを開き、
Mobile Notificationsを選んでInstallすれば導入完了。
次にEdit/Project Settings…の
Mobile Notificationsの項目からAndroidのアイコンとIdentifier(※小文字a-z,0-9,_のみ)を設定します。
なお、Small(ステータス表示用)とLarge(プッシュ通知表示用)の2種類が必要です。
ちなみにアイコン用の画像はRead/Writeを有効にしておく必要があります。
iOSの方はアイコンの設定は必要ありませんが、Request Authorization on App Launchを有効にして
アプリの起動時に通知を出して良いかの許可ウインドウを表示するようにしておきます。
Mobile Notificationsでローカルプッシュ通知を実装
ここからは実際に通知をプログラムから実装する方法です。
まずAndroidは最初にチャンネル登録をします。
#if UNITY_ANDROID //チャンネルのID(なんでもいい) private static readonly string CHANEL_ID = "CHANEL_ID"; #endif
#if UNITY_ANDROID //チャンネルの登録 var channel = new AndroidNotificationChannel(){ Id = CHANEL_ID, //チャンネルID Name = "YAKUZA", //チャンネルの名前(なんでもいい) Importance = Importance.High,//重要度の設定 Description = "Description", //通知の説明(なんでもいい) }; AndroidNotificationCenter.RegisterNotificationChannel(channel); #endif
あとはiOS、Androidそれぞれでプッシュ通知の登録用処理を実装するだけ。
/// <summary> /// プッシュ通知を登録 /// </summary> public void AddSchedule(string title, string message, int badgeCount, int elapsedTime){ #if UNITY_IOS //iOS用の実装 iOSNotificationCenter.ScheduleNotification(new iOSNotification(){ Identifier = $"_notification_{elapsedTime}",//各プッシュ通知の識別子、個別に通知を取り消し場合に使う Title = title, Body = message, ShowInForeground = false, Badge = badgeCount, Trigger = new iOSNotificationTimeIntervalTrigger(){ TimeInterval = new TimeSpan(0, 0, elapsedTime), Repeats = false } }); #elif UNITY_ANDROID //Android用の実装 var notification = new AndroidNotification{ Title = title, Text = message, Number = badgeCount, SmallIcon = "small",//アイコンのIdentifierを指定 LargeIcon = "large",//アイコンのIdentifierを指定 FireTime = DateTime.Now.AddSeconds(elapsedTime) }; AndroidNotificationCenter.SendNotification(notification, CHANEL_ID); #endif }
実際に使ってみると以下のような感じに。
//バッチのカウント1で60秒後にローカルプッシュ通知登録 AddSchedule("タイトル", "メッセージ", 1, 60);
なお、登録したプッシュ通知の削除は以下のような感じで行えます。
//通知とバッジを全て削除 #if UNITY_IOS //iOS用の実装 iOSNotificationCenter.RemoveAllScheduledNotifications(); iOSNotificationCenter.RemoveAllDeliveredNotifications(); iOSNotificationCenter.ApplicationBadge = 0; #elif UNITY_ANDROID //Android用の実装 AndroidNotificationCenter.CancelAllScheduledNotifications(); AndroidNotificationCenter.CancelAllNotifications(); #endif
例えばアプリがバックグラウンドから戻った時に消したりすると良いかもしれません。
public void OnApplicationPause(bool paused){ if (paused){ return; } /*ここで通知とバッジを全て削除とか*/ }