Ich versuche, Benachrichtigungen über GCM in meinem Xamarin.Forms-Projekt zu implementieren. Hier ist mein Codexamarin.forms GCM empfängt keine Nachrichten
MainActivity
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;
}
}
}
Mein RegistrationIntentService.cs
hier ************ ist meine Anwendung Nummer erhalten von Google Wiedergabe API-Konsole
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);
}
}
}
Mein 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());
}
}
}
Schließlich Mein 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>
der obige Code Sie sind alle in meinem Client App für Benachrichtigungen empfangen hier Jetzt Code ist, wie ich das Senden von Nachrichten
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);
}
}
}
}
Hier
ist Antwort vom Server
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}"
Ich bin nicht verstehen, wo ich falsch bin.
Bitte helfen Amit Saraf
Vielen Dank für Ihre Antwort. Beim Senden einer Nachricht durch den Postboten erhalten Sie einen Fehler "Unauthorized Access" 401 –
@AmitSaraf Sie benötigen einen Header namens "Authorization" "key = XXXXX" und "Sender" "id = XXX", die auf die GCM-Projekt-IDs verweisen –