[Unity] 實作原生 APP 本地通知功能 --- Mobile Notifications

發表日期:
2019.11.19
/
分類:
「Unity Mobile Notifications Package」是一套 Unity 官方提供的擴充包,它已經幫你實作完成大多的本地通知功能,開發者僅需設定基本參數即可輕易地對本地裝置發

「Unity Mobile Notifications Package」是一套 Unity 官方提供的擴充包,它已經幫你實作完成大多的本地通知功能,開發者僅需設定基本參數即可輕易地對本地裝置發送系統的原生通知。

說明文件


基本用法

https://www.youtube.com/watch?v=z4k4P8UYy50

第一步 新增一個 Android 專案,從 Window 中開啟 Package Manager。

第二步 找到 Mobile Notifications 後按下 Install 進行安裝。

第三步 開啟 Player Settings,切換到 Other Settings,定義一個有效的 Package Name 並將 Minimum API Level 切換到 Android 4.4 以上版本。

第四步 新增一個空物件與 Script 並掛接,並開啟 Script 編輯腳本。這邊將要實作的是「當 APP 開啟時,跳出最高級警示通知」的 Android 版本。

首先在腳本最前面加入引用字串:

using Unity.Notifications.Android;

在 Start 中實體化 AndroidNotificationChannel 並定義頻道 ID 與 警示分級 Importance 等資訊後進行註冊。
頻道註冊完畢後,往後推送通知都要經過這個頻道來工作,所以 channel_id 非常重要,請謹慎取名。

var c = new AndroidNotificationChannel() {
	Id = "channel_id",
	Name = "Default Channel",
	Importance = Importance.High,
	Description = "Generic notifications"
};
AndroidNotificationCenter.RegisterNotificationChannel(c);

最後就是撰寫通知,可直接接在後面繼續寫。實體化 AndroidNotification 並定義標題 Title、內容 Text 與 發布時間 FireTime,最後用 SendNotification 進行推送。

var notification = new AndroidNotification() {
	Title = "Test Notification",
	Text = "Hello World",
	FireTime = System.DateTime.Now
};
AndroidNotificationCenter.SendNotification(notification, "channel_id");

全部的 Code:

using UnityEngine;
using Unity.Notifications.Android;
public class Notification : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        var c = new AndroidNotificationChannel() {
            Id = "channel_id",
            Name = "Default Channel",
            Importance = Importance.High,
            Description = "Generic notifications"
        };
        AndroidNotificationCenter.RegisterNotificationChannel(c);
        var notification = new AndroidNotification() {
            Title = "Test Notification",
            Text = "Hello World",
            FireTime = System.DateTime.Now
        };
        AndroidNotificationCenter.SendNotification(notification, "channel_id");
    }
}

輸出預覽:

comments powered by Disqus