Unity公式のMobile Notificationsパッケージ(v2.4.0)を使って、
iOSとAndroidで共通コードベースの通知処理を実装する方法をまとめました。
端末ごとの制約や落とし穴(特にiOSのカスタムサウンド)についても解説しています。
環境・使用パッケージ
- Unity 2022.3 LTS
- Mobile Notifications
com.unity.mobile.notifications@2.4.0
Android側の通知処理
通知チャンネル登録
var channel = new AndroidNotificationChannel()
{
Id = "default_channel",
Name = "Default Channel",
Importance = Importance.Default,
Description = "Generic notifications",
};
AndroidNotificationCenter.RegisterNotificationChannel(channel);
通知送信
var notification = new AndroidNotification();
notification.Title = "お知らせ";
notification.Text = "〇〇の時間です";
notification.FireTime = DateTime.Now.AddSeconds(10);
notification.SmallIcon = "icon_01";
AndroidNotificationCenter.SendNotification(notification, "default_channel");
カスタムサウンド
res/raw/customsound.ogg を用意
以下のように設定:
notification.Sound = "customsound";
iOS側の通知処理
通知送信
var notification = new iOSNotification();
notification.Identifier = "notify_01";
notification.Title = "お知らせ";
notification.Body = "〇〇の時間です";
notification.ShowInForeground = true;
notification.Sound = new iOSNotificationSound() { Name = "customsound.caf" };
iOSNotificationCenter.ScheduleNotification(notification);
注意点
customsound.caf は Assets/Plugins/iOS/ に配置
拡張子付きで指定する必要あり(例:customsound.caf)
PostProcessBuildでiOS設定を自動化
[PostProcessBuild]
public static void OnPostProcess(BuildTarget target, string pathToBuiltProject)
{
if (target == BuildTarget.iOS)
{
var plistPath = Path.Combine(pathToBuiltProject, "Info.plist");
var plist = new PlistDocument();
plist.ReadFromFile(plistPath);
var rootDict = plist.root;
var bgModes = rootDict.CreateArray("UIBackgroundModes");
bgModes.AddString("remote-notification");
File.WriteAllText(plistPath, plist.WriteToString());
}
}
共通化の実装方針
プラットフォームごとに処理を分け、トリガーは共通関数で管理:
public void ScheduleLocalNotification()
{
#if UNITY_ANDROID
SendAndroidNotification();
#elif UNITY_IOS
SendIOSNotification();
#endif
}
まとめ
Unity Mobile Notificationsで通知は両OS対応できる
Android:通知チャンネル+res/rawの設定
iOS:caf形式の音声+PostProcessBuildで自動化
#if UNITY_XXX で処理を明確に分離するのがベスト
ブログでもUnityや個人開発ネタを発信中です!
開発ノウハウやアプリ制作過程、Unity連携系のハマりポイントなど
より深掘りした内容をブログにまとめています。
▶ https://syunpp.com
公開中のアプリ一覧はこちら!
実際にUnityで開発してリリース済みのアプリ一覧をまとめています。
▶ https://syunpp.com/公開中のアプリ一覧/