LoginSignup
8
0

More than 3 years have passed since last update.

【Unity】ローカル通知/PUSH  Mobile Notifications

Posted at

体力ゲージが満タンになったとか、デイリーミッションが復活したよとかをスマホに通知してユーザをアプリへ誘導する機能について。
相変わらずメモ書き程度の記述。そのうち本にでもしたいなぁ。

「Mobile Notifications」使います。

理由は無料なのとUnityの付属機能だから今後Androidのバージョンが変わってもサポートを期待できるため。

■インストール
Window > Package Managerを選択。Packagesから「Mobile Notifications」を選択してインストール。Projectに「Mobile Notifications」があればインストール成功。

■設定
Project Settingsでアイコン画像を設定できたりする。

APIのレベルが足りなくなった場合はPlayer Settings > Othersからminsdkを変更。

■実装
マニュアルはここ。
https://docs.unity3d.com/Packages/com.unity.mobile.notifications@1.0/manual/index.html

マニュアルいきなり読んでもよくわからないので、実施したことをメモメモ。

NotificationManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using Unity.Notifications.Android;
using System;

public class NotificationsManager : MonoBehaviour
{
    private string m_channelId = "ここm_channelId";
    private void Awake()
    {
        // 通知用のチャンネルを作成
        //チャンネル情報は通知に表示されない。
        var c = new AndroidNotificationChannel
        {
            Id = m_channelId,
            Name = "ここName",
            Importance = Importance.High,
            Description = "ここDescription",

        };
        AndroidNotificationCenter.RegisterNotificationChannel(c);
    }

    //通知の関数 関数名は自由につける
    public void DoNotification()
    {
        // 通知を送信する
        var n = new AndroidNotification
        {
            Title = "ここTitle",
            Text = "ここText",
            //アイコンはなくても動く
            //SmallIcon = "icon_0",
            //LargeIcon = "icon_1",
            //FireTime = DateTime.Now.AddSeconds(10), // 10 秒後に通知
            FireTime = DateTime.Now.AddSeconds(30), // 10 秒後に通知

        };      
        AndroidNotificationCenter.SendNotification(n, m_channelId);

    }
}

■呼び出しタイミング
遊んでいる最中に通知送ってもしょうがないので、遊んでいないときに通知を送る方法を模索します。

OnApplicationPauseで呼び出すと、ホーム画面や他のアプリに移っても通知が実施される(なぜかたまに通知来ないけど)。

■通知のキャンセル
通知のキャンセルをしないと、フォアグラウンドに復帰したのに通知が来るハメになります。

通知のキャンセルは
CancelAllScheduledNotifications()
を使う。

仕様はこちら
https://docs.unity3d.com/Packages/com.unity.mobile.notifications@1.0/api/Unity.Notifications.Android.AndroidNotificationCenter.html

通知予定をキャンセルしてくれるので、通知が来なくなります。

ちなみに通知済みをキャンセル(削除)してくれるのがこちら。
CancelAllDisplayedNotifications()

これを走らせると、アプリ復帰時に通知済みを削除するので、通知がすっきりします。

なのでこんな感じに。

private void OnApplicationPause(bool pause)
{
    //一時停止(ホームボタンを押す)
    if (pause)
    {
        DoNotification();
    }
    //再開時
    else
    {
        AndroidNotificationCenter.CancelAllDisplayedNotifications();
        AndroidNotificationCenter.CancelAllScheduledNotifications();
    }
}

■課題
この機能はunityの機能を使っているっぽいので、unity(アプリ)が落ちると通知が来なくなる。アプリが落ちてる時こそ通知で再来訪してほしいんだけど。。。

この辺は今後のUnityのアップデートに期待かな。

8
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
0