GCM推送通知不适用于xamarin android

时间:2016-06-15 06:58:57

标签: android xamarin push-notification xamarin.android

我正在尝试在xamarin项目中实现推送通知,我使用设备令牌,我尝试使用APNS & GCM Online Tester进行通知测试,成功发送通知,但没有上设备,请告诉我我在哪里做错了,以下是我的代码

MyGcmListenerService

namespace GCMSample
{
[Service(Exported = false), IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" })]
public class MyGcmListenerService : GcmListenerService
{
    public override void OnMessageReceived(string from, Bundle data)
    {
        var message = data.GetString("message");
        Log.Debug("MyGcmListenerService", "From:    " + from);
        Log.Debug("MyGcmListenerService", "Message: " + message);
       // SendNotification(message);
    }

    void SendNotification(string message)
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

        var notificationBuilder = new Notification.Builder(this)
            .SetSmallIcon(Resource.Drawable.Icon)
            .SetContentTitle("GCM Message")
            .SetContentText(message)
            .SetAutoCancel(true)
            .SetContentIntent(pendingIntent);

        var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
        notificationManager.Notify(0, notificationBuilder.Build());
    }
}
}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gcmsample" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="23" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.gcmsample.permission.C2D_MESSAGE" />
<permission android:name="com.gcmsample.permission.C2D_MESSAGE"
          android:protectionLevel="signature" />

<receiver android:name="com.google.android.gms.gcm.GcmReceiver"
          android:exported="true"
          android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
  <action android:name="com.google.android.c2dm.intent.RECEIVE" />
  <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
  <category android:name="com.gcmsample" />
</intent-filter>
</receiver>

<service
       android:name="com.gcmsample.MyGcmListenerService"
       android:exported="false">
<intent-filter>
  <action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>

<application android:label="GCMSample"></application>
</manifest>

1 个答案:

答案 0 :(得分:3)

我使用相同的推送通知服务,它工作正常我认为你应该注册密钥ID,我在这里分享我的代码请看这个。

using System.Text;
using Android.App;
using Android.Content;
using Android.Util;
using PushSharp.Client;
using Test.Android;
using Test.Core;
using System;


[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")] //, ProtectionLevel = Android.Content.PM.Protection.Signature)]
[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 Test.Android
{
    //You must subclass this!
    [BroadcastReceiver(Permission=GCMConstants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new string[] { GCMConstants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "@PACKAGE_NAME@" })]
    public class PushHandlerBroadcastReceiver : PushHandlerBroadcastReceiverBase<PushHandlerService>
    {
        public static string[] SENDER_IDS = new string[] {"800741969012"};

        public const string TAG = "Test";
    }

    [Service] //Must use the service tag
    public class PushHandlerService : PushHandlerServiceBase
    {
        Intent uiIntent;
        public PushHandlerService() : base(PushHandlerBroadcastReceiver.SENDER_IDS) { }

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

        protected override void OnUnRegistered (Context context, string registrationId)
        {
            Log.Verbose(PushHandlerBroadcastReceiver.TAG, "GCM Unregistered: " + registrationId);
        }

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

            var msg = new StringBuilder();
            var alert = "";

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

                alert = intent.Extras.Get ("alert").ToString();
            }

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

            var pref = ApplicationContext.GetSharedPreferences ("MyPref",FileCreationMode.Private);
            var  editor = pref.Edit (); 
            string isPush = pref.GetString ("Push", "").ToString();

            Console.WriteLine ("isPush : " + isPush);

            if(isPush != null && isPush != ""){
                createNotification("New Message", alert);
            }

        }

        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
            if (Util.userID != null) {
                uiIntent = new Intent (this, typeof(MessageCenterActvity));
            } else {
                uiIntent = new Intent (this, typeof(MainActivity));
            }

            //Create the notification
            var notification = new Notification(Android.Resource.Drawable.logo, title);

            //Auto cancel will remove the notification once the user touches it
            notification.Flags = NotificationFlags.AutoCancel;

            //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);
        }
    }
}