前期項目一直用的是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/添加一個項目 如圖:
這裡我創建一個項目叫:XamarinAndroidFCM。創建好後像下麵這樣:
這一步暫時就創建到這裡,我們需要一個android app的Package 名稱, 下麵我們將創建一個android項目創建好以後再回來設置這個包的名稱。
在Azure上創建一個NotificationHub
登錄到Azure 在雲端在左邊的菜單中找到NotificationHub項, 點擊想創建一個Notification Hub Namespaces, 然後進入NameSpace並且創建一個NotificaitonHub。
然後點擊創建的NotificaitonHub名字進入設置界面,並且點擊中間的菜單GCM(google),設置這個API key
這個key 來自上一步創建的Firebase 項目:
這樣FCM 和Notifaction Hub就關聯好了。
創建一個Xiamarin android APP 並關聯上 NotificationHub和 Firebase Cloud Message
打開VS 創建一個xiamarin for Android的項目。創建好後如下:
打開項目將的配置文件: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中去 並保存。
保存完成後點擊右邊的google-service.json 文件下載到本地並加入到創建的android項目中
這樣FCM的相關設置就完了。
在android的項目中做FCM 以及Azure NotificationHub的連接並接收消息
1. 添加相關的依賴包: Xamarin.Firebase.Messaging 和 Xamarin.Azure.NotificationHubs.Android
2. 設置google-service.json 的build action 為“GoogleServicesJson”(如果找不到這一項,重啟一下VS重新設置就可以找到了)
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>
如下:
4. 配置Notification Hub 賬號到代碼中。
在項目中創建一個Class 叫:Constants, 並創建兩個常量用於保存NotificaiotnHub的連接字元串和名稱。打開azrue中創建的Hub 點擊左邊的Access Policy,看到如下界面:
將DefaultListenSharedAccessSignature的Connection String值拷貝到剛剛創建的那個常量 ListenConnectionString 中。並把Notificaiton Hub的名字保存在
NotificationHubName中。
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 進入到測試界面進行測試:
手機端接收到的消息如下:
總結,Notificaiton Hub + FCM發送消息比較簡單,但是也有許多坑,設置比較多,比如應用包的大小寫問題,FQ的問題都是一些小的阻礙,但是這個消息推送還是比較穩定的, 適合一些國外的項目。 如果做國內的項目可以考慮Notification Hub+ 百度message來做消息推送,當然也可以原則一些第三方的SDK來做。
源碼下載地址: https://github.com/Xushlin/PushNotificaiton