Click here to Skip to main content
15,888,351 members
Articles / Web Development / ASP.NET
Tip/Trick

Android GCM Push Notification

Rate me:
Please Sign up or sign in to vote.
4.83/5 (16 votes)
6 Aug 2012CPOL 269.1K   19   51
Android GCM Push Notification

Introduction

In this tip, I will try to explain how we can integrate a push notification service for Android using ASP.NET and C#. We all know that mobile applications are booming the market trend. Some custom mobile applications use the push notification service to give updates to application users. Here I will explain how we can use Google’s GCM push notification service.

Using the Code 

Class file "AndroidGCMPushNotification.cs":

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Collections.Specialized;

public class AndroidGCMPushNotification
{
	public AndroidGCMPushNotification()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    public string SendNotification(string deviceId, string message)
    {
        string GoogleAppID = "google application id";        
        var SENDER_ID = "9999999999";
        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}", 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 + "";
        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;
    }
}

You can call SendNotification function by passing device Id and Message.

C#
AndroidGCMPushNotification apnGCM = new AndroidGCMPushNotification();

string strResponse =
apnGCM.SendNotification("17BA0791499DB908433B80F37C5FBC89B870084B",
"Test Push Notification message ");

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Project Lead
MCTS - .NET Framework 4.0, Web Applications

Blog : http://thakkermukund.wordpress.com
Twitter@thakkermukund

Don't code today, what you can't debug tomorrow!
Everything makes sense in someone's mind

Comments and Discussions

 
QuestionHow to get device/token id Pin
Member 111376635-Jul-17 22:32
Member 111376635-Jul-17 22:32 
QuestionRegarding Response Pin
swatisrivastava6-Apr-17 21:20
swatisrivastava6-Apr-17 21:20 
QuestionGetting Invalid Registration Error Pin
swatisrivastava6-Apr-17 20:42
swatisrivastava6-Apr-17 20:42 
QuestionSend Image in notification!!! Pin
Member 1285133014-Nov-16 23:20
Member 1285133014-Nov-16 23:20 
Questionhow to push notification using FireBase from wcf service Pin
beniv15-Aug-16 1:55
beniv15-Aug-16 1:55 
C#
public string SendNotification1()

       {
           string deviceId;
           string serverApiKey;
           string result;

           try
           {
               DataAccess.Rregullimi_i_property_ve_ne_StartUP();

               lidhaj_dbDataContext db = new lidhaj_dbDataContext(DataAccess.ConString);

               var tokeni = from p in db.Users
                            select p.Token;

               deviceId = tokeni.First();


               serverApiKey = "XXXXXXXXXXXXXXXXXXXXXXXX-XXXX";

                         WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
               tRequest.Method = "post";

               tRequest.Headers.Add(string.Format("Authorization: key={0}", serverApiKey));

               tRequest.ContentType = "application/json";


               var data = new
               {
                   to = deviceId,
                   message = new
                   {
                       body = "This is the message",
                       title = "This is the title",
                       //icon = "myicon"
                   }
               };

               var serializer = new JavaScriptSerializer();
               var json = serializer.Serialize(data);

               Byte[] byteArray = Encoding.UTF8.GetBytes(json);




               tRequest.ContentLength = byteArray.Length;

               using (Stream dataStream = tRequest.GetRequestStream())
               {
                   dataStream.Write(byteArray, 0, byteArray.Length);

                   using (WebResponse tResponse = tRequest.GetResponse())
                   {
                       using (Stream dataStreamResponse = tResponse.GetResponseStream())
                       {
                           using (StreamReader tReader = new StreamReader(dataStreamResponse))
                           {
                               String sResponseFromServer = tReader.ReadToEnd();

                               // String sResponseFromServer = tReader.ReadToEnd();
                               result = sResponseFromServer;


                           }
                       }
                   }
               }



           }
           catch (Exception ex)
           {
               result = ex.Message;

           }

           return result;


    }


I'm getting missing registration but with this key it works fine in php

my php code


PHP
<?php 

	function send_notification ($tokens, $message1)
	{
		

		$url = 'https://fcm.googleapis.com/fcm/send';
		$fields = array(
			 'registration_ids' => $tokens,
			 'data' => $message1
			);
	
			$headers = array(			
			'Authorization:key =XXXXXXXXXXXXXXXXx-XXXX,
			'Content-Type: application/json'
			);
			
			
	   $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_POST, true);
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);  
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
       $result = curl_exec($ch);           
       if ($result === FALSE) {
           die('Curl failed: ' . curl_error($ch));
       }
       curl_close($ch);
       return $result;
	}
	

	$conn = mysqli_connect("localhost","root","","fcm2");

	$sql = " Select Token From users";

	$result = mysqli_query($conn,$sql);
	$tokens = array();

	if(mysqli_num_rows($result) > 0 ){

		while ($row = mysqli_fetch_assoc($result)) {
			$tokens[] = $row["Token"];
		}
	}

	mysqli_close($conn);

	$message1 = array("message1" => "My message");
	$message_status = send_notification($tokens, $message1);
	echo $message_status ;



 ?>



any suggestion it urgent please
QuestionHow to send Images in notification Pin
Member 1158380322-Jul-16 3:16
Member 1158380322-Jul-16 3:16 
QuestionLine of Code and googleappID Pin
Member 121249087-Jun-16 23:20
Member 121249087-Jun-16 23:20 
QuestionWhere do I find the values that I need to insert? Pin
LorenzKaiser29-Mar-16 22:47
LorenzKaiser29-Mar-16 22:47 
AnswerRe: Where do I find the values that I need to insert? Pin
Gayan Buddhika31-May-16 15:56
professionalGayan Buddhika31-May-16 15:56 
QuestionWant to send push notification to bulk devices Pin
pdsweetpd22815-Mar-16 1:53
pdsweetpd22815-Mar-16 1:53 
QuestionStill Getting 401 Unauthorized Pin
Azurath3-Jan-16 20:09
Azurath3-Jan-16 20:09 
Generalworking fine for me Pin
prashantbathani11-Dec-15 2:38
prashantbathani11-Dec-15 2:38 
QuestionGetting error SenderId MisMatched Pin
Member 1035665225-May-15 18:59
Member 1035665225-May-15 18:59 
GeneralPlagiarism alert Pin
Sriram Sakthivel26-Mar-15 2:53
Sriram Sakthivel26-Mar-15 2:53 
GeneralRe: Plagiarism alert Pin
Mukund Thakker26-Mar-15 19:14
professionalMukund Thakker26-Mar-15 19:14 
Questionsending a message to multiple registration_id at a time Pin
mannmadhan26-Feb-15 2:18
mannmadhan26-Feb-15 2:18 
QuestionGetting also MissingRegistration Pin
Member 953115620-Jan-15 21:54
Member 953115620-Jan-15 21:54 
AnswerRe: Getting also MissingRegistration Pin
Mukund Thakker22-Jan-15 1:02
professionalMukund Thakker22-Jan-15 1:02 
SuggestionNo need to "SENDER_ID" Pin
Bebosh9-Dec-14 3:00
Bebosh9-Dec-14 3:00 
GeneralRe: No need to "SENDER_ID" Pin
Member 1080461018-Apr-16 3:13
Member 1080461018-Apr-16 3:13 
QuestionCan we send push notification to bulk mobiles device tokens and get status of each mobile device token? Pin
Member 101345284-Dec-14 18:26
Member 101345284-Dec-14 18:26 
GeneralExcellent Work Pin
Rungta Atul2-Dec-14 9:13
Rungta Atul2-Dec-14 9:13 
Question401 Error Pin
Denysiuk Roman26-Sep-14 4:38
Denysiuk Roman26-Sep-14 4:38 
QuestionERROR Pin
Prashant77220-Aug-14 20:12
Prashant77220-Aug-14 20:12 
QuestionID's mess Pin
leos7930-Jun-14 20:20
leos7930-Jun-14 20:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.