2017-02-10 17 views
2

Я новичок в этом. Пример андроида от GetStartedFirebaseНе получать уведомления с помощью лазурного центра уведомлений при использовании тега

Ниже приведены шаги:

1) Я установить андроид на мой телефон

2) я последовал за этот пример, чтобы создать мой веб-апи HTTPS // документы .microsoft.com/EN-US/лазурь/уведомление-концентраторы/уведомления-концентраторы-САШ-бэкенд-GCM-андроид-толчок-пользователь-Google-уведомление

3) я закомментируйте класс AuthenticationTestHandler

4) я называю ниже кода из скрипки

Объект DeviceRegistration

{ 
    "Platform": "gcm", 
    "Handle": "regid i get from android", 
    "Tags": [ 
    "1", 
    "2" 
    ] 
} 

// Это создает или обновляет регистрацию (с предоставленной channelURI) по указанному идентификатору

 public async Task<HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate) 
    { 
     RegistrationDescription registration = null; 
     switch (deviceUpdate.Platform) 
     { 
      case "mpns": 
       registration = new MpnsRegistrationDescription(deviceUpdate.Handle); 
       break; 
      case "wns": 
       registration = new WindowsRegistrationDescription(deviceUpdate.Handle); 
       break; 
      case "apns": 
       registration = new AppleRegistrationDescription(deviceUpdate.Handle); 
       break; 
      case "gcm": 
       registration = new GcmRegistrationDescription(deviceUpdate.Handle); 
       break; 
      default: 
       throw new HttpResponseException(HttpStatusCode.BadRequest); 
     } 

     registration.RegistrationId = id; 

     var username = "test"; 

     string[] userTag = new string[1]; 
     userTag[0] = "username:" + username; 
     registration.Tags = new HashSet<string>(userTag); 
     try 
     { 
      await hub.CreateOrUpdateRegistrationAsync(registration); 
     } 
     catch (MessagingException e) 
     { 
      ReturnGoneIfHubResponseIsGone(e); 
     } 

     return Request.CreateResponse(HttpStatusCode.OK); 
    } 

5) Затем я звоню для отправки push-уведомления

http://localhost:4486/api/Notifications?pns=gcm&to_tag=test

public async Task<HttpResponseMessage> Post(string pns, [FromBody]string message, string to_tag) 
{ 

    var user = "test"; 
    message = "msg"; 
    string[] userTag = new string[1]; 
    userTag[0] = "username:" + to_tag;  

    Microsoft.Azure.NotificationHubs.NotificationOutcome outcome = null; 
    HttpStatusCode ret = HttpStatusCode.InternalServerError; 

    switch (pns.ToLower()) 
    { 
     case "wns": 
      // Windows 8.1/Windows Phone 8.1 
      var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" + 
         "From " + user + ": " + message + "</text></binding></visual></toast>"; 
      outcome = await Notifications.Instance.Hub.SendWindowsNativeNotificationAsync(toast, userTag); 
      break; 
     case "apns": 
      // iOS 
      var alert = "{\"aps\":{\"alert\":\"" + "From " + user + ": " + message + "\"}}"; 
      outcome = await Notifications.Instance.Hub.SendAppleNativeNotificationAsync(alert, userTag); 
      break; 
     case "gcm": 
      // Android 
      var notif = "{ \"data\" : {\"message\":\"" + "From " + user + ": " + message + "\"}}"; 
      outcome = await Notifications.Instance.Hub.SendGcmNativeNotificationAsync(notif, userTag); 
      break; 
    } 

    if (outcome != null) 
    { 
     if (!((outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Abandoned) || 
      (outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Unknown))) 
     { 
      ret = HttpStatusCode.OK; 
     } 
    } 

    return Request.CreateResponse(ret); 
} 

Ошибка не возвращена, но я не получаю уведомления.

Я пытаюсь удалить usertag, как показано ниже:

outcome = await Notifications.Instance.Hub.SendGcmNativeNotificationAsync(notif); 

Я могу получить уведомление.

Почему тэг не работает?

Любая помощь приветствуется.

+0

Не могли бы вы пройти через [руководящие принципы Diagnosis] (https://docs.microsoft.com/en-us/azure/notification-hubs/notification-hubs-push-notification -fixer) и обновить вопрос тем, что вы узнали? –

ответ

0

Я в замешательстве - JSON от Fiddler показывает, что регистрация имеет метки «1» и «2», но везде в коде используется тег «имя пользователя: тест». Вы можете получить эту регистрацию из концентратора и убедиться, что у нее есть правильные теги? Вы можете использовать GetRegistrationAsync<TRegistrationDescription>(String) [1], GetRegistrationsByChannelAsync(String, Int32) [2] или GetAllRegistrationsAsync(Int32) [3] способы получить регистрацию.

[1] https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.notificationhubclient#Microsoft_Azure_NotificationHubs_NotificationHubClient_GetRegistrationAsync__1_System_String_

[2] https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.notificationhubclient#Microsoft_Azure_NotificationHubs_NotificationHubClient_GetRegistrationsByChannelAsync_System_String_System_Int32_

[3] https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.notificationhubclient#Microsoft_Azure_NotificationHubs_NotificationHubClient_GetAllRegistrationsAsync_System_Int32_

+0

Первоначально я включил теги «1» и «2» из параметра, но он не работает, поэтому я просто пытаюсь использовать только один тег из регистрации и игнорировать те тег из параметра и вызывать функцию уведомления api также только одним тегом, чтобы видеть если он работает. к сожалению, все еще не в состоянии работать. – terrance019

+0

До Microsoft.Azure.NotificationHubs.NotificationOutcome result = null; Я использовал GetAllRegistrationsAsync (0) для проверки, у него есть одно тег «имя пользователя: тест» – terrance019

2
var allRegistrations = await Notifications.Instance.Hub.GetAllRegistrationsAsync(0); 

Проверьте тег в allRegistrations. Если он там, то он должен работать.

Вы можете проверить уведомление теста из http://pushtry.com