Сбой push-уведомлений концентратора уведомлений Azure или доставка неверных или неполных данных

Я использую следующий php-код для отправки push-уведомлений в приложение Android с помощью концентратора уведомлений Azure.

$hub = new NotificationHub("Endpoint=sb://ServiceName.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SharedAccessKey", "ServiceNameNotification");

$message = '{"data":{"message":"This is a sample notification","title":"Sample Notification","action":"Test","action_id":"60"}}';
$notification = new AzureNotification("gcm", $message);
$hub->sendNotification($notification, null);

Но, к сожалению, в большинстве случаев уведомление не доставляется, хотя я получаю 201 как ответ. Всякий раз, когда он доставляется, результаты непредсказуемы, иногда содержимое старых уведомлений в конечном итоге отображается.

Следующий код используется для отображения уведомлений в приложении Android (Xamarin.Android):

using System;
using Android.App;
using Android.Content;
using Gcm.Client;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json.Linq;
using ServiceName.Helpers;

[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
//GET_ACCOUNTS is needed only for Android versions 4.0.3 and below
[assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
namespace ServiceName.Droid
{
[BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE },
Categories = new string[] { "@PACKAGE_NAME@" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK },
Categories = new string[] { "@PACKAGE_NAME@" })]
[IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY },
Categories = new string[] { "@PACKAGE_NAME@" })]
public class ServiceNameBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService>
{
public static string[] senderIDs = new string[] { Constants.SenderID };

public const string TAG = "MyBroadcastReceiver-GCM";
}
// The ServiceAttribute must be applied to the class.
[Service]
public class PushHandlerService : GcmServiceBase
{

public static string RegistrationID { get; private set; }

public PushHandlerService() : base(ServiceNameBroadcastReceiver.senderIDs) { }
protected override void OnMessage(Context context, Intent intent)
{
string message = string.Empty;
string title = string.Empty;
string action = string.Empty;
string action_id = string.Empty;
if (intent.Extras.ContainsKey("title"))
{
title = intent.Extras.Get("title").ToString();
}
if (intent.Extras.ContainsKey("message"))
{
message = intent.Extras.Get("message").ToString();
}
if (intent.Extras.ContainsKey("action"))
{
action = intent.Extras.Get("action").ToString();
}
if (intent.Extras.ContainsKey("action_id"))
{
action_id = intent.Extras.Get("action_id").ToString();
}

// Extract the push notification message from the intent.
if (!string.IsNullOrWhiteSpace(message) || !string.IsNullOrWhiteSpace(title))
{
// Create a notification manager to send the notification.
var notificationManager =
GetSystemService(Context.NotificationService) as NotificationManager;

// Create a new intent to show the notification in the UI.
PendingIntent contentIntent =
PendingIntent.GetActivity(context, 0,
new Intent(this, typeof(MainActivity)), 0);

// Create the notification using the builder.
var builder = new Notification.Builder(context);
builder.SetAutoCancel(false);
if (!string.IsNullOrWhiteSpace(title))
{
builder.SetContentTitle(title);
}
else
{
builder.SetContentTitle("Notification from ServiceName");
}
if (!string.IsNullOrWhiteSpace(message))
{
builder.SetContentText(message);
}
else
{
builder.SetContentText("Hello ServiceName User");
}
builder.SetSmallIcon(Resource.Drawable.ic_stat_icon);
builder.SetContentIntent(contentIntent);
var notification = builder.Build();

// Display the notification in the Notifications Area.
notificationManager.Notify(1, notification);

}
}
protected override void OnError(Context context, string errorId)
{
System.Diagnostics.Debug.WriteLine(
string.Format("Error occurred in the notification: {0}.", errorId));
}
protected override async void OnRegistered(Context context, string registrationId)
{
System.Diagnostics.Debug.WriteLine("The device has been registered with GCM.", "Success!");

// Get the MobileServiceClient from the current activity instance.
MobileServiceClient client = MainActivity.CurrentActivity.CurrentClient;
var push = client.GetPush();

// Define a message body for GCM.
const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\", \"title\": \"$(titleParam)\", \"action\":\"$(actionParam)\",\"action_id\":\"$(action_idParam)\"}}";

// Define the template registration as JSON.
JObject templates = new JObject();
templates["genericMessage"] = new JObject
{
{"body", templateBodyGCM }
};

try
{
// Make sure we run the registration on the same thread as the activity,
// to avoid threading errors.
MainActivity.CurrentActivity.RunOnUiThread(
// Register the template with Notification Hubs.
async () => {

try
{
await push.RegisterAsync(registrationId, templates);

System.Diagnostics.Debug.WriteLine(
string.Format("Push Installation Id " + push.InstallationId.ToString()));var res = await MiscServices.RegisterDevice(Settings.UserID, Settings.AccessToken, push.InstallationId.ToString(), "gcm");
if ((bool)res.data)
{
System.Diagnostics.Debug.WriteLine("Registered InstallationId in Server");
}
else
{
System.Diagnostics.Debug.WriteLine("Cannot register with Server" + " " + res.status.StatusCode);
}

}
catch (Exception e)
{
}

});}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(
string.Format("Error with Azure push registration: {0}", ex.Message));
}
}

protected override void OnUnRegistered(Context context, string registrationId)
{
System.Diagnostics.Debug.WriteLine("Unregistered with Azure push registration");
}
}

}

Даже тестовые уведомления иногда не доставляются, но в основном тестовые уведомления работают нормально. Мы не можем понять, где происходит проблема, любая помощь очень ценится.

0

Решение

Как вы успешно отправили сообщения в Azure NH, и получили 201 ответ. Когда вы отправляете уведомление через Notification Hubs, сначала оно просто ставится в очередь для NH, чтобы выполнить обработку, чтобы выяснить все его цели, а затем в конечном итоге NH отправляет его в PNS.

Это означает, что когда вы используете REST API или любой из клиентских SDK, успешный возврат вашего вызова только означает, что сообщение было успешно поставлено в очередь в Notification Hub.

Это не дает представление о том, что произошло, когда NH в конце концов отправил сообщение в PNS. Если ваше уведомление не приходит на клиентское устройство, есть вероятность, что когда NH попытался доставить сообщение в PNS, произошла ошибка, например, размер полезной нагрузки превысил максимально допустимый PNS, или учетные данные, настроенные в NH, недействительны и т. д.

Чтобы получить представление об ошибках PNS, мы ввели свойство EnableTestSend. Это свойство автоматически включается при отправке тестовых сообщений с портала или клиента Visual Studio и, следовательно, позволяет просматривать подробную информацию об отладке.

Или вы можете попробовать позвонить через RESTful API для устранения неполадок:
https://mynamespace.servicebus.windows.net/mynotificationhub/messages?api-version=2013-10&test

Пожалуйста, обратитесь к Центры уведомлений Azure — рекомендации по диагностике для получения дополнительной информации.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector