別のスレッドでこれに回答しましたが、ここで繰り返します。コードは少し長く見えますが、機能します。C# プロジェクトで次のコードを実装して 2 日間苦労した後、携帯電話にプッシュ通知を送信しました。この実装に関するリンクを参照しましたが、ここに投稿することができませんでした。私のコードをあなたと共有します。通知をオンラインでテストする場合は、このリンクにアクセスしてください。
注 : apiKey、deviceId、postData をハードコードしました。リクエストで apiKey、deviceId、postData を渡し、メソッド本体から削除してください。メッセージ文字列も渡したい場合
public string SendGCMNotification(string apiKey, string deviceId, string postData)
{
string postDataContentType = "application/json";
apiKey = "AIzaSyC13...PhtPvBj1Blihv_J4"; // hardcorded
deviceId = "da5azdfZ0hc:APA91bGM...t8uH"; // hardcorded
string message = "Your text";
string tickerText = "example test GCM";
string contentTitle = "content title GCM";
postData =
"{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
"\"data\": {\"tickerText\":\"" + tickerText + "\", " +
"\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
//
// MESSAGE CONTENT
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//
// CREATE REQUEST
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = postDataContentType;
Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//
// SEND MESSAGE
try
{
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
return responseLine;
}
catch (Exception e)
{
}
return "error";
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
apiKey、deviceId などの言葉になじみがないかもしれません。それらが何であるか、それらを作成する方法を説明しますので、心配しないでください。
apiKey 説明
と理由 :これは、GCM サーバーにリクエストを送信するときに使用されるキーです。
作成方法 :この投稿を参照
deviceId 説明
と理由 : この ID は、RegistrationId とも呼ばれます。これは、デバイスを識別するための一意の ID です。特定のデバイスに通知を送信する場合は、この ID が必要です。
作成方法: アプリケーションの実装方法によって異なります。コルドバの場合、単純なpushNotification プラグイン を使用しました。このプラグインを使用して、deviceId/RegistrationId を簡単に作成できます。これを行うには、 senderIdが必要です。Google senderId の作成方法は本当に簡単です =)
誰か助けが必要な場合は、コメントを残してください。
ハッピーコーディング。
-チャリサ-