经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
Windows Azure NotificationHub+Firebase Cloud Message 实现消息推动(付源码)
来源:cnblogs  作者:蓝之风  时间:2018/12/19 9:02:20  对本文有异议

前期项目一直用的是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的时候也是一样, 测试了很多次才找出来这个原因

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1"
  2. 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节点中加入以下配置:

  1. <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
  2. <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true"
  3. android:permission="com.google.android.c2dm.permission.SEND">
  4. <intent-filter>
  5. <action android:name="com.google.android.c2dm.intent.RECEIVE" />
  6. <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
  7. <category android:name="${applicationId}" />
  8. </intent-filter>
  9. </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.

  1. using System.Collections.Generic;
  2. using Android.App;
  3. using Android.Util;
  4. using WindowsAzure.Messaging;
  5. using Firebase.Iid;
  6.  
  7. namespace XamarinAndroidFCM
  8. {
  9. [Service]
  10. [IntentFilter(new[] {"com.google.firebase.INSTANCE_ID_EVENT"})]
  11. public class MyFirebaseIidService : FirebaseInstanceIdService
  12. {
  13. private const string Tag = "MyFirebaseIIDService";
  14. NotificationHub _hub;
  15.  
  16. public override void OnTokenRefresh()
  17. {
  18. var refreshedToken = FirebaseInstanceId.Instance.Token;
  19. Log.Debug(Tag, "FCM token: " + refreshedToken);
  20. SendRegistrationToServer(refreshedToken);
  21. }
  22.  
  23. void SendRegistrationToServer(string token)
  24. {
  25. // Register with Notification Hubs
  26. _hub = new NotificationHub(Constants.NotificationHubName,Constants.ListenConnectionString, this);
  27.  
  28. var tags = new List<string>() { "1" };
  29. var regID = _hub.Register(token, tags.ToArray()).RegistrationId;
  30. Log.Debug(Tag, $"Successful registration of ID {regID}");
  31. }
  32. }
  33. }

6. 创建接收消息的服务:MyFirebaseMessagingService 用于接收消息并显示给用户:

  1. using System;
  2. using System.Linq;
  3. using Android.App;
  4. using Android.Content;
  5. using Android.Util;
  6. using Android.Widget;
  7. using Firebase.Messaging;
  8.  
  9. namespace XamarinAndroidFCM
  10. {
  11. [Service]
  12. [IntentFilter(new[] {"com.google.firebase.MESSAGING_EVENT"})]
  13. public class MyFirebaseMessagingService : FirebaseMessagingService
  14. {
  15. private const string Tag = "MyFirebaseMsgService";
  16. public override void OnMessageReceived(RemoteMessage message)
  17. {
  18. Log.Debug(Tag, "From: " + message.From);
  19. if (message.GetNotification() != null)
  20. {
  21. //These is how most messages will be received
  22. Log.Debug(Tag, "Notification Message Body: " + message.GetNotification().Body);
  23. SendNotification(message.GetNotification().Body);
  24. }
  25. else
  26. {
  27. //Only used for debugging payloads sent from the Azure portal
  28. CreateNotification("Test FCM", message.Data.Values.First(), "15:30");
  29. }
  30. }
  31.  
  32. void SendNotification(string messageBody)
  33. {
  34. var intent = new Intent(this, typeof(MainActivity));
  35. intent.AddFlags(ActivityFlags.ClearTop);
  36. var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
  37.  
  38. var notificationBuilder = new Notification.Builder(this)
  39. .SetContentTitle("FCM Message")
  40. .SetSmallIcon(Resource.Drawable.ic_launcher)
  41. .SetContentText(messageBody)
  42. .SetAutoCancel(true)
  43. .SetContentIntent(pendingIntent);
  44.  
  45. var notificationManager = NotificationManager.FromContext(this);
  46. notificationManager.Notify(0, notificationBuilder.Build());
  47. }
  48.  
  49. void CreateNotification(string title, string desc, string time)
  50. {
  51. var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
  52. var uiIntent = new Intent(this, typeof(MainActivity));
  53. var notification = new Notification(Resource.Mipmap.ic_launcher, title);
  54. notification.Flags = NotificationFlags.AutoCancel;
  55. notification.Defaults = NotificationDefaults.All;
  56. notification.Vibrate = new long[] { 0, 100, 200, 300 };
  57. if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean)
  58. {
  59. var contentView = new RemoteViews(PackageName, Resource.Layout.Custom_Notification);
  60. contentView.SetTextViewText(Resource.Id.txtTitle, title);
  61. contentView.SetTextViewText(Resource.Id.txtTime, time);
  62. contentView.SetTextViewText(Resource.Id.txtContent, desc);
  63. notification.BigContentView = contentView;
  64. }
  65. notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, PendingIntentFlags.UpdateCurrent));
  66.  
  67. var rnd = new Random();
  68. var notificationId = rnd.Next(10000, 99999);
  69.  
  70. notificationManager.Notify(notificationId, notification);
  71. }
  72. }
  73. }

 

代码部分全部实现完成。

测试

打开模拟器或手机,设置代理, 调试应用, 并且再次打开Azure Notifiaciton Hub 进入到测试界面进行测试:

image

 

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

image

 

总结,Notificaiton Hub + FCM发送消息比较简单,但是也有许多坑,设置比较多,比如应用包的大小写问题,FQ的问题都是一些小的阻碍,但是这个消息推送还是比较稳定的, 适合一些国外的项目。 如果做国内的项目可以考虑Notification Hub+ 百度message来做消息推送,当然也可以原则一些第三方的SDK来做。

源码下载地址: https://github.com/Xushlin/PushNotificaiton

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号