c# - xamarin.forms GCM 未接收消息

标签 c# android visual-studio google-cloud-messaging xamarin.forms

我正在尝试在我的 Xamarin.Forms 项目中通过 GCM 实现通知。这是我的代码

主 Activity

using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Gms.Common;
using Android.Content;

namespace AIA.Droid
{
    [Activity (Theme = "@style/MyTheme",
        ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            global::Xamarin.Forms.Forms.Init (this, bundle);
            LoadApplication (new AIA.App ());

            var x = typeof(Xamarin.Forms.Themes.DarkThemeResources);
            x = typeof(Xamarin.Forms.Themes.LightThemeResources);
            x = typeof(Xamarin.Forms.Themes.Android.UnderlineEffect);

            if (IsPlayServicesAvailable())
            {
                var intent = new Intent(this, typeof(RegistrationIntentService));
                StartService(intent);
            }
        }

        public bool IsPlayServicesAvailable()
        {
            int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
            if (resultCode != ConnectionResult.Success)
                return false;
            else
                return true;
        }
    }
}

我的 RegistrationIntentService.cs enter image description here

这里 ************ 是我从 Google Play API 控制台收到的申请编号

using System;    
using Android.App;
using Android.Content;
using Android.Util;
using Android.Gms.Gcm;
using Android.Gms.Gcm.Iid;

namespace AIA.Droid
{
    [Service(Exported = false)]
    class RegistrationIntentService : IntentService
    {
        static object locker = new object();

        public RegistrationIntentService() : base("RegistrationIntentService") { }

        protected override void OnHandleIntent(Intent intent)
        {
            try
            {
                Log.Info("RegistrationIntentService", "Calling InstanceID.GetToken");
                lock (locker)
                {
                    var instanceID = InstanceID.GetInstance(this);
                    var token = instanceID.GetToken(
                        "************", GoogleCloudMessaging.InstanceIdScope, null);

                    Log.Info("RegistrationIntentService", "GCM Registration Token: " + token);
                    SendRegistrationToAppServer(token);
                    Subscribe(token);
                }
            }
            catch (Exception e)
            {
                Log.Debug("RegistrationIntentService", "Failed to get a registration token");
                return;
            }
        }

        void SendRegistrationToAppServer(string token)
        {
            // Add custom implementation here as needed.
        }

        void Subscribe(string token)
        {
            var pubSub = GcmPubSub.GetInstance(this);
            pubSub.Subscribe(token, "/topics/global", null);
        }
    }
}

我的 MyGcmListenerService.cs

using Android.App;
using Android.Content;
using Android.OS;
using Android.Gms.Gcm;
using Android.Util;

namespace AIA.Droid
{
    [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("Akola Industries Association")
                .SetContentText(message)
                .SetDefaults(NotificationDefaults.Sound)
                .SetContentIntent(pendingIntent);

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

最后是我的 AndroidMainfeast

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.AIA.Droid" android:installLocation="auto" android:versionCode="1" android:versionName="1.0">
    <uses-sdk android:minSdkVersion="16" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="com.AIA.Droid.permission.C2D_MESSAGE" />
  <uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"></uses-permission>
  <permission android:name="com.AIA.Droid.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <application android:label="AIA" android:icon="@drawable/Icon">
    <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.AIA.Droid" />
      </intent-filter>
    </receiver>
  </application>
</manifest>

上述所有代码都在我的客户端应用程序中,用于接收通知 现在这是我发送消息的代码 enter image description here

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace MessageSender
{
    class Program
    {
        public const string API_KEY = "My_API_Key";
        public const string MESSAGE = "Welcome to AIA";

        static void Main(string[] args)
        {
            var jGcmData = new JObject();
            var jData = new JObject();

            jData.Add("message", MESSAGE);
            jGcmData.Add("to", "/topics/global");
            jGcmData.Add("data", jData);

            var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    client.DefaultRequestHeaders.TryAddWithoutValidation(
                        "Authorization", "key=" + API_KEY);

                    Task.WaitAll(client.PostAsync(url,
                        new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
                            .ContinueWith(response =>
                            {
                                Console.WriteLine(response);
                                Console.WriteLine("Message sent: check the client device notification tray.");
                            }));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Unable to send GCM message:");
                Console.Error.WriteLine(e.StackTrace);
            }
        }
    }
}

服务器响应

Id = 13, Status = RanToCompletion, Method = "{null}", Result = "StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:\r\n{\r\n  X-Content-Type-Options: nosniff\r\n  X-Frame-Options: SAMEORIGIN\r\n  X-XSS-Protection: 1; mode=block\r\n  Alt-Svc: quic=\":443\"; ma=2592000; v=\"36,35,34,33,32\"\r\n  Vary: Accept-Encoding\r\n  Transfer-Encoding: chunked\r\n  Accept-Ranges: none\r\n  Cache-Control: max-age=0, private\r\n  Date: Tue, 25 Oct 2016 05:02:12 GMT\r\n  Server: GSE\r\n  Content-Type: application/json; charset=UTF-8\r\n  Expires: Tue, 25 Oct 2016 05:02:12 GMT\r\n}"

我不明白我哪里错了。

请帮忙 阿米特·萨拉夫

最佳答案

这个链接对我理解GCM推送通知的过程有很大帮​​助,你也可以使用POSTMAN来测试推送通知的发送:

http://forums.xamarin.com/discussion/comment/217083/#Comment_217083

How to use Push Notifications in Xamarin Forms

http://xamarinhelp.com/push-notifications/

测试它们: https://stackoverflow.com/a/30778643/1207924

关于c# - xamarin.forms GCM 未接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40232106/

相关文章:

android - 使用 MediaStore android 重命名图像

java - Android - SQLiteDatabase 不维护插入

visual-studio - Visual Studio 的导航栏是否有热键?

android - Firebase ChildEventListener 如果没有检索到数据

visual-studio - 如何在 VS 中仅禁用最大行长度 tslint

c++ - "compile as"设置为 'default' 时出现外部符号链接(symbolic link)错误

c# - C#中的"MoveFile"函数(重启后删除文件)

c# - GridView 找不到定义类型的字段,但找不到匿名类型?

c# - 如何强制关注子窗口直到它关闭

c# - 将 utc 转换为本地日期时间