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


前期項目一直用的是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 牽涉到牆的問題,需要手機能夠翻牆, 否則測試將不能成功,另外,在做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發送消息比較簡單,但是也有許多坑,設置比較多,比如應用包的大小寫問題,翻牆的問題都是一些小的阻礙,但是這個消息推送還是比較穩定的, 適合一些國外的項目。 如果做國內的項目可以考慮Notification Hub+ 百度message來做消息推送,當然也可以用一些第三方的SDK來做。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM