【问题标题】:Xamarin Android using Azure Notification Hub not receiving notifications使用 Azure 通知中心的 Xamarin Android 未收到通知
【发布时间】:2015-06-07 00:14:18
【问题描述】:

我们使用 Xamarin 开发了一个 Android 应用程序,但我们在 Azure 通知中心遇到了问题。我们试图向在我们的 Azure 移动服务中注册的 Android 设备发送推送通知,但没有注册的 Android 设备接收到通知。当我们尝试通过 Azure 门户中的通知中心对其进行调试时,结果显示通知已发送到设备。但是,设备没有收到之前收到的通知。
请让我们知道我们的代码中缺少某些内容(查找下面的代码)或 Azure 通知中心(适用于 Android GCM)中是否有任何问题。

注意:推送通知的所有 android 权限都在下面的同一代码文件中给出,而不是在 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 = "@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 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);


        }



    }
}

【问题讨论】:

    标签: xamarin xamarin.android google-cloud-messaging azure-notificationhub


    【解决方案1】:

    权限是包含 XML 数据的清单文件中的标记。在编译 DVM 时,会检查 Manifest 文件中的权限和其他必要数据以打包到 .apk 中。您应该始终遵循相同的格式。

    请查看tutorial 了解更多信息。

    【讨论】:

    • 它以前工作过。没有在清单中设置权限。即使我尝试过但仍然无法正常工作。
    猜你喜欢
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2017-02-22
    • 2014-12-25
    相关资源
    最近更新 更多