如何在Xamarin Forms中使用推送通知

63

我有一个使用Xamarin.Forms开发的应用,目标平台为IOS、Android和WP 8。

我需要在我的应用中添加推送通知功能。

我看过了pushsharp的演示,它似乎很有前途。但是我所看到的所有代码都是针对每个平台单独完成的。

我希望它能在Xamarin.Forms项目中完成,比如在App.cs文件中,这样我就不需要重复注册设备以及处理推送通知的方式。

欢迎提供示例代码。

编辑: 我根据Idot的答案实现了它。这是我的答案链接


1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Wizche
这完全基于Azure,我正在寻找PushSharp。此外,这不是关于Xamarin Forms,而是针对每个平台的单独实现。 但感谢您为我找到了一些开始的东西。 - Rohit Vipin Mathews
6个回答

57

我几天前刚刚实现了推送通知功能,我将在这里分享我的解决方案 (基于 PushSharp)

步骤指南:

1) 在您的共享项目中,创建一个名为IPushNotificationRegister的接口。

public interface IPushNotificationRegister
{
    void ExtractTokenAndRegister();
}

此接口用于获取推送令牌并将其发送到服务器。该令牌每台设备唯一。

2) 在您共享的项目中,应调用ExtractTokenAndRegister(使用您喜欢的IOC,在登录后立即调用它)。

Android实现:

3) 添加接收器以侦听Google GCM服务接收到的事件:

a)

[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class GCMBootReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        MyIntentService.RunIntentInService(context, intent);
        SetResult(Result.Ok, null, null);
    }
}

b)

[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
[assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
[assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]

namespace Consumer.Mobile.Droid.PushNotification
{
    [BroadcastReceiver(Permission = "com.google.android.c2dm.permission.SEND")]
    [IntentFilter(new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { "com.google.android.c2dm.intent.REGISTRATION" }, Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { "com.google.android.gcm.intent.RETRY" }, Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter (new[]{ Intent.ActionBootCompleted }, Categories = new[]{ Intent.CategoryDefault })]
    public class GCMBroadcastReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            MyIntentService.RunIntentInService(context, intent);
            SetResult(Result.Ok, null, null);
        }
    }
}

c) 添加 Intent 服务来处理通知

using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Media;
using Android.OS;
using Android.Support.V4.App;
using Consumer.Mobile.Infra;
using Consumer.Mobile.Services.PushNotification;
using Java.Lang;
using XLabs.Ioc;
using TaskStackBuilder = Android.Support.V4.App.TaskStackBuilder;

namespace Consumer.Mobile.Droid.PushNotification
{
    [Service]
    public class MyIntentService : IntentService
    {
        private readonly ILogger _logger;
        private readonly IPushNotificationService _notificationService;
        private readonly IPushNotificationRegister _pushNotificationRegister;

        public MyIntentService()
        {
            _logger = Resolver.Resolve<ILogger>();
            _notificationService = Resolver.Resolve<IPushNotificationService>();
            _pushNotificationRegister = Resolver.Resolve<IPushNotificationRegister>();
        }

        static PowerManager.WakeLock _sWakeLock;
        static readonly object Lock = new object();


        public static void RunIntentInService(Context context, Intent intent)
        {
            lock (Lock)
            {
                if (_sWakeLock == null)
                {
                    // This is called from BroadcastReceiver, there is no init.
                    var pm = PowerManager.FromContext(context);
                    _sWakeLock = pm.NewWakeLock(
                    WakeLockFlags.Partial, "My WakeLock Tag");
                }
            }

            _sWakeLock.Acquire();
            intent.SetClass(context, typeof(MyIntentService));
            context.StartService(intent);
        }

        protected override void OnHandleIntent(Intent intent)
        {
            try
            {
                Context context = this.ApplicationContext;
                string action = intent.Action;

                if (action.Equals("com.google.android.c2dm.intent.REGISTRATION"))
                {
                    HandleRegistration(context, intent);
                }
                else if (action.Equals("com.google.android.c2dm.intent.RECEIVE"))
                {
                    HandleMessage(context, intent);
                }
            }
            finally
            {
                lock (Lock)
                {
                    //Sanity check for null as this is a public method
                    if (_sWakeLock != null)
                        _sWakeLock.Release();
                }
            }
        }

        private void HandleMessage(Context context, Intent intent)
        {

            Intent resultIntent = new Intent(this, typeof(MainActivity));


            TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);

            var c = Class.FromType(typeof(MainActivity));
            stackBuilder.AddParentStack(c);
            stackBuilder.AddNextIntent(resultIntent);

            string alert = intent.GetStringExtra("Alert");
            int number = intent.GetIntExtra("Badge", 0);

            var imageUrl = intent.GetStringExtra("ImageUrl");
            var title = intent.GetStringExtra("Title");

            Bitmap bitmap = GetBitmap(imageUrl);

            PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .SetAutoCancel(true) // dismiss the notification from the notification area when the user clicks on it
                .SetContentIntent(resultPendingIntent) // start up this activity when the user clicks the intent.
                .SetContentTitle(title) // Set the title
                .SetNumber(number) // Display the count in the Content Info
                .SetSmallIcon(Resource.Drawable.Icon) // This is the icon to display
                .SetLargeIcon(bitmap)
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification))
                .SetContentText(alert); // the message to display.

            // Build the notification:
            Notification notification = builder.Build();

            // Get the notification manager:
            NotificationManager notificationManager =
                GetSystemService(Context.NotificationService) as NotificationManager;

            // Publish the notification:
            const int notificationId = 0;
            notificationManager.Notify(notificationId, notification);
        }

        private void HandleRegistration(Context context, Intent intent)
        {
            var token = intent.GetStringExtra("registration_id");
            _logger.Info(this.Class.SimpleName, "Received Token : " + token);

            if (_pushNotificationRegister.ShouldSendToken(token))
            {
                var uid = Android.Provider.Settings.Secure.GetString(MainActivity.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);
                _notificationService.AddPushToken(token, DeviceUtils.GetDeviceType(), uid);
            }
        }


        private Bitmap GetBitmap(string url)
        {

            try
            {
                System.Net.WebRequest request =
                    System.Net.WebRequest.Create(url);
                System.Net.WebResponse response = request.GetResponse();
                System.IO.Stream responseStream =
                    response.GetResponseStream();
                return BitmapFactory.DecodeStream(responseStream);


            }
            catch (System.Net.WebException)
            {
                return null;
            }

        }

    }
}

d) 实现接口 IPushNotificationRegister:

using Android.App;
using Android.Content;
using Consumer.Mobile.Services;
using Consumer.Mobile.Services.PushNotification;
[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]

// Gives the app permission to register and receive messages.
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]

// Needed to keep the processor from sleeping when a message arrives
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
[assembly: UsesPermission(Name = "android.permission.RECEIVE_BOOT_COMPLETED")]
namespace Consumer.Mobile.Droid.PushNotification
{
    public class PushNotificationRegister : IPushNotificationRegister
    {          
        public override void ExtractTokenAndRegister()
        {
            string senders = AndroidConfig.GCMSenderId;
            Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
            intent.SetPackage("com.google.android.gsf");
            intent.PutExtra("app", PendingIntent.GetBroadcast(MainActivity.Context, 0, new Intent(), 0));
            intent.PutExtra("sender", senders);
            MainActivity.Context.StartService(intent);
        }


    }
}

iOS 实现:

4)在你的 AppDelegate 中,添加以下方法:

a)

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    var deviceTokenString = deviceToken.ToString().Replace("<","").Replace(">", "").Replace(" ", "");
    var notificationService = Resolver.Resolve<IPushNotificationService>();
    var pushNotificationRegister = Resolver.Resolve<IPushNotificationRegister>();

    if (pushNotificationRegister.ShouldSendToken(deviceTokenString))
    {
        var uid = UIDevice.CurrentDevice.IdentifierForVendor.AsString();
        notificationService.AddPushToken(deviceTokenString, DeviceUtils.GetDeviceType(), uid);
    }
}

b) 实现 IPushNotificationRegister 接口:

using Consumer.Mobile.Services;
using Consumer.Mobile.Services.PushNotification;
using UIKit;

namespace Consumer.Mobile.iOS.PushNotification
{
    public class iOSPushNotificationRegister : IPushNotificationRegister
    {
        public override void ExtractTokenAndRegister()
        {
            const UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
            UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
        }
    }
}

关于 WP,我没有实现它。

如果您需要在服务器端使用 PushSharp 的代码,请告诉我。

您可以在这里查看我基于的客户端示例 here


谢谢。我一定会看看的。不,我不需要服务器端代码。 - Rohit Vipin Mathews
1
你在哪里处理IOS的DidReceiveRemoteNotification - Rohit Vipin Mathews
我没有这样做,如果你想在应用程序运行时添加自定义显示通知的行为,你需要在AppDelegate类中处理它: public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo) {} - IdoT
正如我上面所述,我使用了PushSharp,如果您对实现有疑问,请提出问题,我很乐意回答,因为这与客户端实现无关。 - IdoT
实际上,我找不到IPushNotificationService接口。我应该在哪里找到它? - Anik Saha
显示剩余12条评论

17
我被Xamarin支持和Forms建议使用以下插件。

这个插件运行良好。

https://github.com/rdelrosario/xamarin-plugins/tree/master/PushNotification

一旦我让它正常工作,就会更新答案。

更新:

我已经成功实现了iOS和Android的推送通知。

我使用了Google Cloud Messaging Client,这是一个非常好的Android组件,不需要像this answer中提到的那样编写太多代码。

我的iOS实现与this类似,所需的代码也不多。

至于从服务器推送通知,我使用了PushSharp的nuget包。

我没有在WP上实现,因为这不是我的项目要求。

如果您打算实现推送通知,请阅读此Xamarin Help on Push Notifications

更新(2018年6月)- 在iOS和Android上使用以下插件进行FCM,它支持Xamarin.Forms - FirebasePushNotificationPlugin


这个解决方案是否适用于Android 5+?从我所看到的来看,GCM组件会导致崩溃,是这样吗? - Ingenator
我没有发现任何问题,我会再次确认并尽快回复。如果您遇到崩溃,请分享具体的错误信息。 - Rohit Vipin Mathews
谢谢,这个插件是否支持GCM的主题,以便服务器无需获取registration_ids并订阅主题的客户端应用程序。 - Shivang Gupta
有人可以告诉我为什么我收到新的推送通知时,之前的通知会被替换吗?:( - Vishnu Babu
@VishnuBabu - notificationManager.Notify(notificationId, notification); 中的 notificationId 是通知 ID。 https://dev59.com/cl4b5IYBdhLWcg3whB6V#29141884 - Rohit Vipin Mathews
显示剩余8条评论

2
在Xamarin Forms中,您也可以使用像Donky这样的通知SDK(它是美国Urban Airship的欧洲等效物);您可以轻松地在一天内制作可扩展的通知项目。我曾两次使用此SDK在不到35分钟的时间内构建过WhatsApp克隆壳。请参见http://docs.mobiledonky.com

1

0

0
最近这里有一篇关于在Xamarin Forms上实现推送通知的博客文章(因为没有基于Forms的实现,所以需要在每个平台上单独实现),使用Azure移动服务。

http://www.xamarinhelp.com/push-notifications/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接