GCM 推送通知不适用于 xamarin android

Posted

技术标签:

【中文标题】GCM 推送通知不适用于 xamarin android【英文标题】:GCM Push Notifications not working on xamarin android 【发布时间】:2016-06-15 06:58:57 【问题描述】:

我正在尝试在 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>

【问题讨论】:

推送通知时能否分享来自设备的 ADB 日志 我正在从apns-gcm.bryantan.info 推送通知,所以没有 ADB 日志 嗯,你仍然可以从设备developer.xamarin.com/guides/android/…获取ADB日志 @Prashant 这里是亚行日志drive.google.com/file/d/0BweRv1OeL66fVUtTeldiSU1mazA/… 【参考方案1】:

我为推送通知使用了相同的服务,它工作得很好,我认为你应该注册密钥 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);
        
    

【讨论】:

@mdDroid 你是如何修复它的?我遇到了同样的问题

以上是关于GCM 推送通知不适用于 xamarin android的主要内容,如果未能解决你的问题,请参考以下文章

安卓设备的 GCM 推送通知不适用于 MI 和乐视手机

当应用程序处于非活动状态时,GCM 推送通知不适用于 iOS

推送通知 php 代码不适用于 Android

TTL 功能不适用于谷歌浏览器推送通知

当 3G 网络可用时,Android GCM 不适用于 wifi 网络

为啥 GCM 推送通知会重复?