如何使用PushSharp获取GCM错误消息“NotRegistered”

时间:2012-11-03 21:30:21

标签: c# android xamarin.android

我正在尝试弄清楚如何获取Google GCM响应(即NotRegistered错误),以便我可以从用户帐户中删除GCM信息。

GCM Archetecture Overview开始(关于从GCM取消注册设备),他们声明“只有当GCM服务器尝试向设备发送消息并且设备回答应用程序已卸载或它已取消注册时,它才会取消注册没有配置接收com.google.android.c2dm.intent.RECEIVE意图的广播接收器。此时,您的服务器应将设备标记为未注册(服务器将收到NotRegistered错误)。“

在PushSharp for Mono for Android中;如何在尝试向用户发送消息时获得Google Response,而是从Google收到“NotRegistered错误”?要发送消息,我有以下代码:

    var push = new PushService();

    // setup channel settings: sender id, access key, registration package name
    var settings = new GcmPushChannelSettings(<>, <>, <PACKAGE>);
    push.StartGoogleCloudMessagingPushService(settings);
    var android = NotificationFactory.AndroidGcm();
    android = android.ForDeviceRegistrationId(GCM_Id); 
        push.QueueNotification(android.WithJson("{\"alert\":\"" + message + "\",\"URL\":\"" + URL + "\"}")); 

如何获取Google的回复以了解1.消息是否已经完成2.应用程序已卸载或3.收到NotRegistered错误,以便我可以从用户帐户中删除GCM ID?

期待我能得到任何帮助。上面的代码使用PushSharp for Mono for Android(MonoDroid),它可以在向用户发送消息时完美运行。 PushSharp非常棒,我强烈建议您通过GCM向用户发送消息。

1 个答案:

答案 0 :(得分:1)

您需要订阅EventsPushService属性附带的事件。

然后,您就可以在事件处理程序中收到回复。

        //Create our service    
        PushService push = new PushService();

        //Wire up the events
        push.Events.OnDeviceSubscriptionExpired += new Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
        push.Events.OnDeviceSubscriptionIdChanged += new Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
        push.Events.OnChannelException += new Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
        push.Events.OnNotificationSendFailure += new Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
        push.Events.OnNotificationSent += new Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
        push.Events.OnChannelCreated += new Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
        push.Events.OnChannelDestroyed += new Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);

在您的事件处理程序中,您可以检查异常并确定是否应从用户帐户中删除设备ID。

        static void Events_OnNotificationSendFailure(Common.Notification notification, Exception notificationFailureException)
        {
            // Remove device id 
            Console.WriteLine("Failure: " + notification.Platform.ToString() + " -> " + notificationFailureException.Message + " -> " + notification.ToString());
        }