Windows Azure NotificationHub+Firebase Cloud Message 實現消息推動(付源碼)

来源:https://www.cnblogs.com/vaiyanzi/archive/2018/12/18/10138312.html
-Advertisement-
Play Games

前期項目一直用的是Windows azure NotificationHub+Google Cloud Message 實現消息推送, 但是GCM google已經不再推薦使用,慢慢就不再維護了, 現在Google 主推 FCM, 另一方面,google在android生態中的許可權要求越來越嚴格,不 ...


前期項目一直用的是Windows azure NotificationHub+Google Cloud Message 實現消息推送, 但是GCM google已經不再推薦使用,慢慢就不再維護了, 現在Google 主推 FCM, 另一方面,google在android生態中的許可權要求越來越嚴格,不像以前那樣將許可權聲明在AndroidManifest中,在安裝的時候做一次提醒就好了, 現在對於一些主要的許可權需要動態申請並且用戶同意才能使用,比如調用相機,使用電話本等等,同樣對於後臺的常駐服務也做了一定的限制,旨在提升android系統的用戶體驗以及提高電池的續航時間,在2018-11-1強制執行編譯的Target SDK API Leve必須是26+,否則是不允許上Goolge Play , GCM也只支持到2019-11-1,之後就不再支持,項目老的推送服務要依賴於後臺常駐Service。 基於以上原因我對當前的android項目做了一次全面升級。這裡分享一下GCM到FCM的遷移過程。

我們的項目用的微軟的Azure平臺,自然所有的一切技術都圍繞著Windows Azure 平臺展開。 Web App, Web API 使用的是Azure Cloud Service, Mobile APP 使用的是Xamarin, 資料庫使用的是Azure SQL Database, 是不是很微軟系。

自然在消息推送的時候想到的還是Azure平臺上的技術 Notification Hub。

名詞解釋:

GCM: Google Cloud Message.

FCM: Firebase Cloud Message.

遷移步驟

1. 創建一個Firebase 項目並且開啟Firebase Cloud Messaging功能。

2. 在Azure上創建一個NotificationHub。

3.將Firebase和ConnectionHub關聯上。

4.創建一個Xiamarin android APP 並關聯上 NotificationHub和 Firebase Cloud Message。

5. 測試消息發送。

註意:由於需要連接到Firebase Cloud Message 牽涉到牆的問題,需要手機能夠FQ, 否則測試將不能成功,另外,在做FCM的設置也是寸步難行。

準備工作

1. 需要一個google賬號,用於創建Firebase 項目並開啟 Firebase Cloud Message。

2.需要一個azure賬號,用於創建NotificationHub。

3.Visual Studio 並且要安裝Xamarin 插件。

4. 準備一個VPN 用於測試。

創建一個Firebase 項目並且開啟Firebase Cloud Messaging功能

打開 Firebase 開發控制台https://console.firebase.google.com/添加一個項目 如圖:

image

 

這裡我創建一個項目叫:XamarinAndroidFCM。創建好後像下麵這樣:

image

這一步暫時就創建到這裡,我們需要一個android app的Package 名稱, 下麵我們將創建一個android項目創建好以後再回來設置這個包的名稱。

在Azure上創建一個NotificationHub

登錄到Azure 在雲端在左邊的菜單中找到NotificationHub項, 點擊想創建一個Notification Hub Namespaces, 然後進入NameSpace並且創建一個NotificaitonHub。

image

然後點擊創建的NotificaitonHub名字進入設置界面,並且點擊中間的菜單GCM(google),設置這個API key

image

這個key 來自上一步創建的Firebase 項目:

image

這樣FCM 和Notifaction Hub就關聯好了。

創建一個Xiamarin android APP 並關聯上 NotificationHub和 Firebase Cloud Message

打開VS 創建一個xiamarin for Android的項目。創建好後如下:

image

打開項目將的配置文件:AndroidManifest.xml, 將裡面的包名改成小寫(這裡很重要,如果不改成小寫,你將不會收到任何消息,這是個坑,做GCM的時候也是一樣, 測試了很多次才找出來這個原因

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" 
          android:versionName="1.0" package="xamarinandroidfcm.xamarinandroidfcm">

這裡我們將這個包名“xamarinandroidfcm.xamarinandroidfcm” 填到第一步FCM中去 並保存。

image

保存完成後點擊右邊的google-service.json 文件下載到本地並加入到創建的android項目中

image

這樣FCM的相關設置就完了。

在android的項目中做FCM 以及Azure NotificationHub的連接並接收消息

1. 添加相關的依賴包: Xamarin.Firebase.Messaging 和 Xamarin.Azure.NotificationHubs.Android

image

 

image

 

2. 設置google-service.json 的build action 為“GoogleServicesJson”(如果找不到這一項,重啟一下VS重新設置就可以找到了

image

3. 在AndroidManifest.xmal 的Application節點中加入以下配置:

<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
		<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" 
		          android:permission="com.google.android.c2dm.permission.SEND">
			<intent-filter>
				<action android:name="com.google.android.c2dm.intent.RECEIVE" />
				<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
				<category android:name="${applicationId}" />
			</intent-filter>
		</receiver>

如下:

image

4. 配置Notification Hub 賬號到代碼中。

在項目中創建一個Class 叫:Constants, 並創建兩個常量用於保存NotificaiotnHub的連接字元串和名稱。打開azrue中創建的Hub 點擊左邊的Access Policy,看到如下界面:

image

將DefaultListenSharedAccessSignature的Connection String值拷貝到剛剛創建的那個常量 ListenConnectionString 中。並把Notificaiton Hub的名字保存在

NotificationHubName中。

 

image

5.創建MyFirebaseIidService 服務類用於接收和刷新Firebase的token, 並將token以及tag註冊到Notificationhub.

using System.Collections.Generic;
using Android.App;
using Android.Util;
using WindowsAzure.Messaging;
using Firebase.Iid;

namespace XamarinAndroidFCM
{
    [Service]
    [IntentFilter(new[] {"com.google.firebase.INSTANCE_ID_EVENT"})]
    public class MyFirebaseIidService : FirebaseInstanceIdService
    {
        private const string Tag = "MyFirebaseIIDService";
        NotificationHub _hub;

        public override void OnTokenRefresh()
        {
            var refreshedToken = FirebaseInstanceId.Instance.Token;
            Log.Debug(Tag, "FCM token: " + refreshedToken);
            SendRegistrationToServer(refreshedToken);
        }

        void SendRegistrationToServer(string token)
        {
            // Register with Notification Hubs
            _hub = new NotificationHub(Constants.NotificationHubName,Constants.ListenConnectionString, this);

            var tags = new List<string>() { "1" };
            var regID = _hub.Register(token, tags.ToArray()).RegistrationId;
            Log.Debug(Tag, $"Successful registration of ID {regID}");
        }
    }
}

6. 創建接收消息的服務:MyFirebaseMessagingService 用於接收消息並顯示給用戶:

using System;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Util;
using Android.Widget;
using Firebase.Messaging;

namespace XamarinAndroidFCM
{
    [Service]
    [IntentFilter(new[] {"com.google.firebase.MESSAGING_EVENT"})]
    public class MyFirebaseMessagingService : FirebaseMessagingService
    {
        private const string Tag = "MyFirebaseMsgService";
        public override void OnMessageReceived(RemoteMessage message)
        {
            Log.Debug(Tag, "From: " + message.From);
            if (message.GetNotification() != null)
            {
                //These is how most messages will be received
                Log.Debug(Tag, "Notification Message Body: " + message.GetNotification().Body);
                SendNotification(message.GetNotification().Body);
            }
            else
            {
                //Only used for debugging payloads sent from the Azure portal
                CreateNotification("Test FCM", message.Data.Values.First(), "15:30");
            }
        }

        void SendNotification(string messageBody)
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

            var notificationBuilder = new Notification.Builder(this)
                .SetContentTitle("FCM Message")
                .SetSmallIcon(Resource.Drawable.ic_launcher)
                .SetContentText(messageBody)
                .SetAutoCancel(true)
                .SetContentIntent(pendingIntent);

            var notificationManager = NotificationManager.FromContext(this);
            notificationManager.Notify(0, notificationBuilder.Build());
        }

        void CreateNotification(string title, string desc, string time)
        {
            var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
            var uiIntent = new Intent(this, typeof(MainActivity));
            var notification = new Notification(Resource.Mipmap.ic_launcher, title);
            notification.Flags = NotificationFlags.AutoCancel;
            notification.Defaults = NotificationDefaults.All;
            notification.Vibrate = new long[] { 0, 100, 200, 300 };
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean)
            {
                var contentView = new RemoteViews(PackageName, Resource.Layout.Custom_Notification);
                contentView.SetTextViewText(Resource.Id.txtTitle, title);
                contentView.SetTextViewText(Resource.Id.txtTime, time);
                contentView.SetTextViewText(Resource.Id.txtContent, desc);
                notification.BigContentView = contentView;
            }
            notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, PendingIntentFlags.UpdateCurrent));

            var rnd = new Random();
            var notificationId = rnd.Next(10000, 99999);

            notificationManager.Notify(notificationId, notification);
        }
    }
}

 

代碼部分全部實現完成。

測試

打開模擬器或手機,設置代理, 調試應用, 並且再次打開Azure Notifiaciton Hub 進入到測試界面進行測試:

image

 

手機端接收到的消息如下:

image

 

總結,Notificaiton Hub + FCM發送消息比較簡單,但是也有許多坑,設置比較多,比如應用包的大小寫問題,FQ的問題都是一些小的阻礙,但是這個消息推送還是比較穩定的, 適合一些國外的項目。 如果做國內的項目可以考慮Notification Hub+ 百度message來做消息推送,當然也可以原則一些第三方的SDK來做。

源碼下載地址: https://github.com/Xushlin/PushNotificaiton


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 數據集的下載地址為 https://pan.baidu.com/s/1dtHJiV6zMbf_fWPi-dZ95g 我們要做的是預測貸款用戶是否會逾期。表格中 "status" 是結果標簽:0表示未逾期,1表示逾期。 先對數據進行三七分,隨機種子2018。這裡利用了LR,SVM,DecisionTr ...
  • 問題描述 在我遠程連接我的伺服器資料庫的時候,navicat給我提示了這麼一個錯誤: 思考解決 首先 鑒於前兩天我剛幫別人解決了這個一模一樣的問題,都是錯誤代碼1130,當時解決的方向是:(不過本方法對我而言並沒有生效) 其次 是否可能是mysql的配置中bind-address的問題呢,於是我去找 ...
  • 本文是對MySQL中觸發器的總結,從觸發器概念出發,結合實例對創建觸發器、使用觸發器、刪除觸發器進行介紹。 ...
  • 定義自定義函數 調用 f1 函數 查詢 tmp 表中的數據 在查詢中調用 f1 函數 運行結果: 函數與存儲過程的區別 存儲過程: 1. 裡面包含 SQL 語句 2. intout, out 構造返回值 3. 調用方式:select 函數名(參數) 函數: 1. 裡面不能包含 SQL 語句 2. r ...
  • CHAR_LENGTH(str) 返回值為字元串str 的長度,長度的單位為字元。一個多位元組字元算作一個單字元。 CONCAT(str1,str2,...) 字元串拼接, 如有任何一個參數為NULL ,則返回值為 NULL。 CONCAT_WS(separator,str1,str2,...) 字元 ...
  • 問題 如何安裝並使用Oracle SQL Developer訪問Oracle。 步驟 Oracle SQL Developer是Oracle官方出品的免費圖形化開發工具,相對SQL*Plus來說,圖形化的界面便於操作,不必記憶大量的命令,輸出結果美觀。它的基本功能包括結果的格式化輸出,編輯器自動提示 ...
  • cmd命令中輸入:adb shell dumpsys activity activities 在一連串的輸出中找到Runing activities com.android.settings是包名. .HWSettings是activitie名稱 ...
  • 本文由雲+社區發表 SQLite 在移動端開發中廣泛使用,其使用質量直接影響到產品的體驗。 常見的 SQLite 質量監控一般都是依賴上線後反饋的機制,比如耗時監控或者用戶反饋。這種方式問題是: 事後發現,負面影響已經發生。 關註的只是沒這麼差。eg. 監控閾值為 500ms ,那麼一條可優化為 2 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...