0
votes

We have developed a Android App using Xamarin and we are facing problem in Azure Notification Hub. We were trying to send push notifications to Android devices registered in our Azure Mobile Service and no registered android devices are receiving the notifications. When we tried to debug it via Notification Hub in Azure Portal, the results are showing that the notifications are sent to the devices. However, the devices are not receiving the notifications which was receiving before.
Kindly let us know either we are missing something in our code (Find the code below) or is there any problem in Azure Notification Hub (for Android GCM).

Note: All the android permissions for push notifications are given in the same code file below and not in the Android manifest.

Our GCM Service Code Below:

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[] { "@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 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);


        }



    }
}
1

1 Answers

0
votes

Permission are tags in the Manifest file that has XML data. While compiling DVM checks the Manifest file for permissions and other necessary data to package in the .apk. You should always follow the same format.

Please have a look at this tutorial for more information.