다른 스레드에서이 질문에 답변했으며 여기에서 반복합니다. 코드는 조금 더 길어 보이지만 작동합니다. 방금 C# 프로젝트에서 다음 코드를 구현하여 2 일 동안 고생 한 후 휴대 전화로 푸시 알림을 보냈습니다. 이 구현과 관련된 링크를 언급했지만 여기에 게시 할 수 없습니다. 그래서 당신과 내 코드를 공유 할 것입니다. 온라인으로 알림을 테스트하려면 link을 방문하십시오.
참고 : 나는 apiKey에, DeviceID가와의 postData를 hardcorded 한 귀하의 요청에 에게 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 서버에 요청을 보낼 때 사용되는이 핵심. 만드는 방법
: Refer this post
의 DeviceID
무엇 & 이유 : 또한 RegistrationId로 알려진이 ID입니다. 이것은 장치를 식별하는 고유 한 ID입니다. 특정 기기에 알림을 보내려면이 ID가 필요합니다.
How to 만들기 : 이것은 응용 프로그램을 구현하는 방법에 따라 다릅니다. 코드바의 경우 간단한 사용 pushNotification Plugin이 플러그인을 사용하여 deviceId/RegistrationId를 만들면됩니다. 그렇게하려면 , , 보낸 사람 ID이 있어야합니다.Google은 보낸 사람을 만드는 방법은 정말 간단합니다 =)
누구든지 도움이 필요하면 의견을 남기십시오.
해피 코딩.
-Charitha-
그렇다면 서버 구현의 용도는 무엇입니까? 설명서에는 다음과 같은 내용이 나와 있습니다. 구현해야하는 타사 응용 프로그램 서버. 이 애플리케이션 서버는 선택한 GCM 연결 서버를 통해 GCM 사용 Android 애플리케이션에 데이터를 전송합니다. 우리가 구현 한 서버가 메시지를 보내는 서버가 아닙니다. – user2857001
백엔드에서해야 할 일은 사용자가 GCM 서버에 등록되고 DB에 저장되면 Android 기기에서 기기 토큰을 수집하는 것뿐입니다. 메시지를 푸시하려면 Google 서버에 기기 토큰과 API를 사용하여 메시지를 보내도록 요청할 수 있습니다. –
오! 따라서 서버는 deviceID를 등록하고 deviceID를 검색하기위한 것입니다. 그리고 기기 A에서 기기 B로 보내기 위해 기기 A는 기기 B의 ID를 서버에서 가져 와서 GCM을 사용하여 기기 B로 알림을 푸시합니다. – user2857001