نحوه ارسال پیام به گوشی اندروید از طریق Asp.net
برای ارسال پیام به گوشی اندروید با استفاده از یک سرویس گوگل ما این کار را انجام می دهیم به این صورت که ابتدا باید در جی سی ام گوگل ثبت نام کرده باشیم تا یک سری از کد ها را در اختیار داشته باشیم
این روش با استفاده از Google GCM انجام میدهیم که به ما SenderId و همچنین GoogleAppID را در اختیار ما قرار میدهد تا ما با استفاده از این ابزار ها بتوانیم پیام خود را مثل وایبر به یک نرم افزار توی اندروید بفرستیم
حالا کدهای سی شارپ سمت سرور بصورت زیر است.
public string SendNotification(string deviceId, string message)
{
//string GoogleAppID = "google application id";
string GoogleAppID = "AIzaSyADMm";
var SENDER_ID = "1049xxxxxxxxx";
var value = message;
value = HttpContext.Current.Server.UrlEncode(value);
//string x = n.;
//Notification message1 = new Notification.Builder().addData("alert", "test message" /*notif.getAlert()*/).build();
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
//tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
tRequest.ContentType = " application/x-www-form-urlencoded";
//tRequest.ContentType = " application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
//string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + "";
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.price=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}