Thursday 28 March 2013

How To Send GCM Push Notification + Android


Step 1:Get your application ID and Sender ID from https://code.google.com/apis/console/

Step 2:Get Device ID using Sender ID in device  following way




/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

  • Add permission into your menifiest

     <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  
        <uses-permission android:name="android.permission.WAKE_LOCK" />

    <permission
        android:name="com.app.getgcmkey.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="com.app.getgcmkey.permission.C2D_MESSAGE" />

  • Add below Receiver and Service into your menifiest

 <receiver
            android:name="com.google.android.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter >
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.app.getgcmkey" />
            </intent-filter>
        </receiver>
       
       
         <service android:name="GCMIntentService" >
        </service>
        


 Here com.app.getgcmkey is your application package name
  • Add gcm.jar from Android SDK into your libs folder

  • Add GCMIntentService service into your application package


package com.app.getgcmkey;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gcm.GCMBaseIntentService;


public class GCMIntentService extends GCMBaseIntentService {

    @SuppressWarnings("hiding")
    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super("senderid");
    }

    @Override
    protected void onError(Context arg0, String arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onMessage(Context arg0, Intent arg1) {

       
        // Get the data from intent and send to notificaion bar
        String response = arg1.getStringExtra("message");
        Log.e("GCM:received", response);
        try {
           
           
        //    Toast.makeText(getApplicationContext(), response, 1).show();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    protected void onRegistered(Context arg0, String registrationId) {
       
        // TODO Auto-generated method stub
        if (registrationId != null) {
        Log.d("regid",registrationId);
       
        }
    }

    @Override
    protected void onUnregistered(Context arg0, String arg1) {
        // TODO Auto-generated method stub
        //Logger.logger("unregistered", arg1);
    }

}

  • Write code to get GCM ID in your activity/service
public void getGCMDeviceID()  {
      
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);

        if (GCMRegistrar.isRegistered(this)) {
            Log.d("info", GCMRegistrar.getRegistrationId(this));
        }
      
        String regId = GCMRegistrar.getRegistrationId(this);
      
        if (regId.equals("")) {
            // replace this with the project ID
            GCMRegistrar.register(this, "909849023929");
          
          
          
          
          
            regId = GCMRegistrar.getRegistrationId(this);
            Log.e("info:regid",   regId);
        } else {
            Log.e("info:regid", "already registered as" + regId);
        }
      
   
   
    }


Server side code: Dot Net 3.5 using web service

using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Net;
using System.Text;
using System.IO;

 [WebMethod]
    public string SendNotification(string deviceId, string message)
    {
        string GoogleAppID = "your app id;
        // 
        var SENDER_ID = "sender id";

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


Thanks..............................................................




No comments:

Post a Comment