0

Мы разработали приложение для Android с использованием Xamarin, и мы столкнулись с проблемой в Azure Notification Hub. Мы пытались отправить push-уведомления на устройства Android, зарегистрированные в нашей Azure Mobile Service, и никакие зарегистрированные устройства Android не получают уведомления. Когда мы попытались отладить его через Notification Hub в Azure Portal, результаты показывают, что уведомления отправляются на устройства. Однако устройства не получают уведомления, которые ранее были получены.
Просьба сообщить нам, что у нас что-то отсутствует в нашем коде (найдите код ниже) или есть какие-либо проблемы в Azure Notification Hub (для Android GCM).Xamarin Android с помощью Azure Notification Hub, не получающего уведомлений

Примечание. Все разрешения на андроид для push-уведомлений приведены в том же файле кода ниже, а не в манифесте Android.

Наша GCM Код обслуживания Ниже:

using System.Text; 
using Android.App; 
using Android.Content; 
using Android.Util; 
using Gcm.Client; 


//VERY VERY VERY IMPORTANT NOTE!!!! 
// Your package name MUST NOT start with an uppercase letter. 
// Android does not allow permissions to start with an upper case letter 
// If it does you will get a very cryptic error in logcat and it will not be obvious why you are crying! 
// So please, for the love of all that is kind on this earth, use a LOWERCASE first letter in your Package Name!!!! 
using ByteSmith.WindowsAzure.Messaging; 
using System.Diagnostics; 
using System.Collections.Generic; 
using System; 

[assembly: Permission(Name = "@[email protected]_MESSAGE")] 
[assembly: UsesPermission(Name = "@[email protected]_MESSAGE")] 
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")] 

//GET_ACCOUNTS is only needed 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 seeMuscatAndroidApp 
{ 
    //You must subclass this! 
    [BroadcastReceiver(Permission= Gcm.Client.Constants.PERMISSION_GCM_INTENTS)] 
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "@[email protected]" })] 
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "@[email protected]" })] 
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "@[email protected]" })] 
    public class PushHandlerBroadcastReceiver : GcmBroadcastReceiverBase<GcmService> 
    { 

     public static string[] SENDER_IDS = new string[] { Constants.SenderID }; 

     public const string TAG = "GoogleCloudMessaging"; 
    } 

    [Service] //Must use the service tag 
    public class GcmService : GcmServiceBase 
    { 
     public static string RegistrationID { get; private set; } 
     private NotificationHub Hub { get; set; } 

     Context _generalContext; 

     public GcmService() : base(PushHandlerBroadcastReceiver.SENDER_IDS) 
     { 
      Log.Info(PushHandlerBroadcastReceiver.TAG, "GcmService() constructor"); 
     } 

     protected override async void OnRegistered (Context context, string registrationId) 
     { 
      Log.Verbose(PushHandlerBroadcastReceiver.TAG, "GCM Registered: " + registrationId); 
      RegistrationID = registrationId; 

      _generalContext = context; 

      //createNotification("GcmService Registered...", "The device has been Registered, Tap to View!"); 

      Hub = new NotificationHub(Constants.NotificationHubPath, Constants.ConnectionString); 
      try 
      { 
       await Hub.UnregisterAllAsync(registrationId); 
      } 
      catch (Exception ex) 
      { 
       Debug.WriteLine(ex.Message); 
       Debugger.Break(); 
      } 


      var tags = new List<string>() { main.userCountry, main.userCity, main.userLatitude, main.userLongitude, main.userPhoneMake, main.userPhoneModel, main.userPhoneName, main.userPhoneAndroidVersion, main.userAppVersion,main.userUID}; 

      Console.WriteLine("///////////HUB TAGS///////////////////"); 
      Console.WriteLine("Country:" + main.userCountry); 
      Console.WriteLine("City:" + main.userCity); 
      Console.WriteLine("Latitude:" + main.userLatitude); 
      Console.WriteLine("Longitude:"+main.userLongitude); 
      Console.WriteLine("Make:" + main.userPhoneMake); 
      Console.WriteLine("Model:" + main.userPhoneModel); 
      Console.WriteLine("Phone Name:" + main.userPhoneName); 
      Console.WriteLine("Android Version:" + main.userPhoneAndroidVersion); 
      Console.WriteLine("App version:" + main.userAppVersion); 
      Console.WriteLine("User ID:" + main.userUID); 
      Console.WriteLine("///////////END OF HUB TAGS///////////////////"); 


      try 
      { 
       var hubRegistration = await Hub.RegisterNativeAsync(registrationId, tags);     
       Debug.WriteLine("RegistrationId:" + hubRegistration.RegistrationId); 
      } 
      catch (Exception ex) 
      { 
       Debug.WriteLine("#########$$$$Error:"+ex.Message); 

      } 
     } 



     protected override void OnUnRegistered (Context context, string registrationId) 
     { 
      Log.Verbose(PushHandlerBroadcastReceiver.TAG, "GCM Unregistered: " + registrationId); 
      //Remove from the web service 
      // var wc = new WebClient(); 
      // var result = wc.UploadString("http://your.server.com/api/unregister/", "POST", 
      //  "{ 'registrationId' : '" + lastRegistrationId + "' }"); 

      //createNotification("GcmService Unregistered...", "The device has been unregistered, Tap to View!"); 
     } 

     protected override void OnMessage (Context context, Intent intent) 
     { 
      Log.Info(PushHandlerBroadcastReceiver.TAG, "GCM Message Received!"); 

      Debug.WriteLine("/********* GCM Received ****************"); 

      var msg = new StringBuilder(); 

      if (intent != null && intent.Extras != null) 
      { 
       foreach (var key in intent.Extras.KeySet()) 
        msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString()); 
      } 

      //Store the message 
      var prefs = GetSharedPreferences(context.PackageName, FileCreationMode.Private); 
      var edit = prefs.Edit(); 
      edit.PutString("last_msg", msg.ToString()); 
      edit.Commit(); 

      string message = intent.Extras.GetString("message"); 
      if (!string.IsNullOrEmpty(message)) 
      { 
       createNotification("New todo item!", "Todo item: " + message); 
       return; 
      } 

      string msg2 = intent.Extras.GetString("msg"); 
      string notititle = intent.Extras.GetString("notititle"); 
      if (!string.IsNullOrEmpty(msg2)) 
      { 
       createNotification(notititle, msg2); 
       return; 
      } 

      // createNotification("PushSharp-GCM Msg Rec'd", "Message Received for C2DM-Sharp... Tap to View!"); 
      //createNotification("Unknown message details", msg.ToString()); 
     } 

     protected override bool OnRecoverableError (Context context, string errorId) 
     { 
      Log.Warn(PushHandlerBroadcastReceiver.TAG, "Recoverable Error: " + errorId); 

      return base.OnRecoverableError (context, errorId); 
     } 

     protected override void OnError (Context context, string errorId) 
     { 
      Log.Error(PushHandlerBroadcastReceiver.TAG, "GCM Error: " + errorId); 
     } 

     void createNotification(string title, string desc) 
     { 
      //Create notification 
      var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; 

      //Create an intent to show ui 
      Intent uiIntent = new Intent(); 
      uiIntent.SetClass(this, typeof(dealsview)); 
      uiIntent.PutExtra("contentID", "todaydeals"); 
      uiIntent.PutExtra("contentName", ""); 
      uiIntent.PutExtra("isSale", ""); 
      //Create the notification 
      var notification = new Notification(Resource.Drawable.Icon, title); 

      //Auto cancel will remove the notification once the user touches it 
      notification.Flags = NotificationFlags.AutoCancel; 
      notification.Defaults = NotificationDefaults.All; 
      //Set the notification info 
      //we use the pending intent, passing our ui intent over which will get called 
      //when the notification is tapped. 
      notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0)); 

      //Show the notification 
      notificationManager.Notify(1, notification); 


     } 



    } 
} 

ответ

0

Разрешение теги в файле манифеста, который имеет данные XML. При компиляции DVM проверяет файл манифеста на наличие разрешений и других необходимых данных для упаковки в .apk. Вы всегда должны придерживаться того же формата.

Для получения дополнительной информации см. Этот tutorial.

+0

Он работал раньше. Без установки разрешений в манифесте. Хотя я и пытался, но все еще не работал. –

Смежные вопросы