2013-04-27 25 views
9

Sono nuovo a tutte le notifiche push GCM Android e ho letto i post dello stack ma non ho potuto ottenere una risposta diretta. Ho anche letto Create push notification in android per ottenere una migliore comprensione di come funziona GCM. Ho anche usato il gcm-demo-server e gcm-demo-client fornito dall'SDK. Tuttavia, qui ci sono i miei dubbi e quello che ho provato finora:Come inviare notifiche push Android tramite GCM su C# .Net

  1. Per quanto riguarda il collegamento che ho messo, il telefono che ha i registri delle app per ottenere la chiave di registrazione. È una chiave unica per tutti i telefoni che utilizzano la stessa app?
  2. Questo codice di registrazione scade in ogni caso? (Ad esempio App in esecuzione su sfondo)
  3. Supponendo che ho la chiave di registrazione, ho provato il seguente frammento di codice per spingere la notifica tramite GCM alla mia app. Questo è scritto su C# .net. Per favore fatemi sapere se ciò che ho detto sopra può essere raggiunto utilizzando il seguente frammento di codice:

     private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json") 
        { 
         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"; 
        } 
    
  4. C'è un modo diretto di invio di notifiche push senza il telefono prima di essere registrati nel nostro server personalizzato?

risposta

19

consultare Codice:

public class AndroidGCMPushNotification 
{ 
    public AndroidGCMPushNotification() 
    { 
     // 
     // TODO: Add constructor logic here 
     // 
    } 
    public string SendNotification(string deviceId, string message) 
    { 
     string SERVER_API_KEY = "server api key";   
     var SENDER_ID = "application number"; 
     var value = message; 
     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.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY)); 

     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() + "&registration_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; 
    } 
} 

Referance Link:

http://www.codeproject.com/Tips/434338/Android-GCM-Push-Notification

+0

Per qualche motivo il codice sopra riportato non funziona. Ho assunto che l'ID dispositivo sia la chiave di registrazione qui. Tuttavia, quando provo a inviare messaggi utilizzando http://helmibaraja.com/gcm_demo.html, funziona. Qualche idea? –

+1

Funziona cambiando "®istration_id =" in "& registration_id =". Grazie a tutti :) –

+2

GoogleAppID = la chiave del server e & deviceid = l'ID di registrazione (184 caratteri) && SENDER_ID = ID di 12 cifre ID (il numero del progetto) (Grazie commenti sulla pagina del progetto codice. –

2

This non ha mai funzionato per me ed è difficile da mettere a punto, più il superamento di un elenco di token di registrazione non è chiaro -Ti si aspettano passando un array di stringhe, invece di separati da virgola stringa -, il fatto che questo è molto semplice richiesta post ho creato il mio classe con un metodo che restituiscono la risposta del server, e funziona molto bene:

Uso

 //Registration Token 
     string[] registrationIds ={"diks4vp5......","erPjEb9....."}; 

     AndroidGcmPushNotification gcmPushNotification = new 
     AndroidGcmPushNotification(
      "API KEY", registrationIds, "Hello World" 
      ); 
     gcmPushNotification.SendGcmNotification(); 

Classe

using System; 
using System.IO; 
using System.Net; 
using System.Text; 
using System.Web.Script.Serialization; 


public class AndroidGcmPushNotification 
{ 
private readonly string _apiAccessKey; 
private readonly string[] _registrationIds; 
private readonly string _message; 
private readonly string _title; 
private readonly string _subtitle; 
private readonly string _tickerText; 
private readonly bool _vibrate; 
private readonly bool _sound; 

public AndroidGcmPushNotification(string apiAccessKey, string[] registrationIds, string message, string title = "", 
    string subtitle = "", string tickerText = "", bool vibrate = true, bool sound = true) 
{ 
    _apiAccessKey = apiAccessKey; 
    _registrationIds = registrationIds; 
    _message = message; 
    _title = title; 
    _subtitle = subtitle; 
    _tickerText = tickerText; 
    _vibrate = vibrate; 
    _sound = sound; 
} 

public string SendGcmNotification() 
{ 

    //MESSAGE DATA 
    GcmPostData data = new GcmPostData() 
    { 
     message = _message, 
     title = _title, 
     subtitle = _subtitle, 
     tickerText = _tickerText, 
     vibrate = _vibrate, 
     sound = _sound 
    }; 

    //MESSAGE FIELDS 
    GcmPostFields fields = new GcmPostFields(); 
    fields.registration_ids = _registrationIds; 
    fields.data = data; 

    //SERIALIZE TO JSON 
    JavaScriptSerializer jsonEncode = new JavaScriptSerializer(); 

    //CONTENTS 
    byte[] byteArray = Encoding.UTF8.GetBytes(jsonEncode.Serialize(fields)); 

    //REQUEST 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send"); 
    request.Method = "POST"; 
    request.KeepAlive = false; 
    request.ContentType = "application/json"; 
    request.Headers.Add($"Authorization: key={_apiAccessKey}"); 
    request.ContentLength = byteArray.Length; 

    Stream dataStream = request.GetRequestStream(); 
    dataStream.Write(byteArray, 0, byteArray.Length); 
    dataStream.Close(); 


    //SEND REQUEST 
    try 
    { 
     WebResponse response = request.GetResponse(); 
     { 
      StreamReader reader = new StreamReader(response.GetResponseStream()); 
      string responseLine = reader.ReadToEnd(); 
      reader.Close(); 

      return responseLine; 
     } 
    } 
    catch (Exception e) 
    { 
     return e.Message; 
    } 

} 
private class GcmPostFields 
{ 
    public string[] registration_ids { get; set; } 
    public GcmPostData data { get; set; } 

} 
private class GcmPostData 
{ 
    public string message { get; set; } 
    public string title { get; set; } 
    public string subtitle { get; set; } 
    public string tickerText { get; set; } 
    public bool vibrate { get; set; } 
    public bool sound { get; set; } 
} 

} 
1

C'è pacchetto PushSharp. permette di comunicare con quasi tutti i api notifica popolare.

codice Esempio:

// Configuration 
var config = new GcmConfiguration ("GCM-SENDER-ID", "AUTH-TOKEN", null); 

// Create a new broker 
var gcmBroker = new GcmServiceBroker (config); 

// Wire up events 
gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { 

    aggregateEx.Handle (ex => { 

     // See what kind of exception it was to further diagnose 
     if (ex is GcmNotificationException) { 
      var notificationException = (GcmNotificationException)ex; 

      // Deal with the failed notification 
      var gcmNotification = notificationException.Notification; 
      var description = notificationException.Description; 

      Console.WriteLine ($"GCM Notification Failed: ID={gcmNotification.MessageId}, Desc={description}"); 
     } else if (ex is GcmMulticastResultException) { 
      var multicastException = (GcmMulticastResultException)ex; 

      foreach (var succeededNotification in multicastException.Succeeded) { 
       Console.WriteLine ($"GCM Notification Failed: ID={succeededNotification.MessageId}"); 
      } 

      foreach (var failedKvp in multicastException.Failed) { 
       var n = failedKvp.Key; 
       var e = failedKvp.Value; 

       Console.WriteLine ($"GCM Notification Failed: ID={n.MessageId}, Desc={e.Description}"); 
      } 

     } else if (ex is DeviceSubscriptionExpiredException) { 
      var expiredException = (DeviceSubscriptionExpiredException)ex; 

      var oldId = expiredException.OldSubscriptionId; 
      var newId = expiredException.NewSubscriptionId; 

      Console.WriteLine ($"Device RegistrationId Expired: {oldId}"); 

      if (!string.IsNullOrWhitespace (newId)) { 
       // If this value isn't null, our subscription changed and we should update our database 
       Console.WriteLine ($"Device RegistrationId Changed To: {newId}"); 
      } 
     } else if (ex is RetryAfterException) { 
      var retryException = (RetryAfterException)ex; 
      // If you get rate limited, you should stop sending messages until after the RetryAfterUtc date 
      Console.WriteLine ($"GCM Rate Limited, don't send more until after {retryException.RetryAfterUtc}"); 
     } else { 
      Console.WriteLine ("GCM Notification Failed for some unknown reason"); 
     } 

     // Mark it as handled 
     return true; 
    }); 
}; 

gcmBroker.OnNotificationSucceeded += (notification) => { 
    Console.WriteLine ("GCM Notification Sent!"); 
}; 

// Start the broker 
gcmBroker.Start(); 

foreach (var regId in MY_REGISTRATION_IDS) { 
    // Queue a notification to send 
    gcmBroker.QueueNotification (new GcmNotification { 
     RegistrationIds = new List<string> { 
      regId 
     }, 
     Data = JObject.Parse ("{ \"somekey\" : \"somevalue\" }") 
    }); 
} 

// Stop the broker, wait for it to finish 
// This isn't done after every message, but after you're 
// done with the broker 
gcmBroker.Stop(); 
7

codice sembra po 'lungo, ma funziona. Ho appena inviato una notifica push al mio telefono dopo aver faticato per 2 giorni implementando il seguente codice nel progetto C#. Ho fatto riferimento a un collegamento relativo a questa implementazione, ma non sono riuscito a trovarlo per postare qui. Quindi condividerò il mio codice con te. Se si desidera verificare la notifica on-line si può visitare a questo link.

nota: ho hardcorded apikey, deviceId e postData, si prega di passare l'apikey, deviceId e postData nella vostra richiesta e rimuoverli dal il corpo del metodo. Se volete passare un messaggio stringa anche

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; 
} 

utente non può familiarità con parole come apikey, deviceId. Non ti preoccupare, spiegherò cosa sono e come crearli.

apikey
Cosa & perché: questa una chiave che verrà utilizzato per l'invio di richieste al server di GCM.
Come creare: Refer this post

deviceId
Cosa & perché: Questo id noto anche come RegistrationId. Questo è un ID univoco per identificare il dispositivo. Quando si desidera inviare una notifica a un dispositivo specifico è necessario questo ID.
Come creare : dipende da come si implementa l'applicazione. Per cordova ho usato un semplice pushNotification Plugin È possibile semplicemente creare un dispositivo IDI/Registrazione utilizzando questo plug-in. Per fare ciò è necessario disporre di a senderId. Google come creare un mittente è molto semplice =)

Se qualcuno ha bisogno di aiuto lascia un commento.

Happy Coding.
-Charitha-

+1

grazie amici ... –

+1

Grt !!! era esattamente alla ricerca di questo grazie – Venkat

+0

controllare questo link https://srimansaswat.wordpress.com/2016/11/15/how-to.. -Inviare-push-notification-to-your-android-device-con-c-codice / –

Problemi correlati