Search This Blog

Monday, March 24, 2014

Send Android Push Notifications via GCM(Google Cloud Messaging) By C#.Net


Create Google Api key  and Client ID 

Please go to https://console.developers.google.com/project   and create new project for using api

After creating new project we will get project number which is necessary for future work.
Please select  "APIs" from left site menu which is under "APIs & auth" .

After selecting   "APIs" we will get avaliable api list in right site listview.For doing Android Push Notifications we need to active "Google Cloud Messaging for Android".Please click "OFF" for making "ON"

After Click "OFF"

Create new Client ID :

Please select  "Credentials" from left site menu which is under "APIs & auth"  and Click "Create new Client ID" button from Write side.

Please fillup the popup window.First select "Installed application" and then select "Android". After that insert "Package name" which will come from you android project and also insert  "Signing certificate fingerprint (SHA1)" which is your project SHA1. Please select "Enabled" option and click "Create Client ID".

After that you will get Client Id which will show inside your "Credential" window.


We will use "884643418365-ho8n0fcn161s2p7uucmkeh727989knuf" as Client ID in the C# code and Android code.


Create new Key :

Click "Create new Key " button from Write side. 

And click "Server Key" from popup window.Then another popup window will come and click again "Create " button without fillup anything.

Then we will get Api Key for server applications
We will use "AIzaSyDD0kNEqml-ToGk08RtLT0w0NNT0VjSIok" as Google Api key  in the C# code .

Android Code
Install Google Cloud messaging  for Android Library  from Android SDK Manager.




Add class inside named GCMService (path: >src>com.test.myexample) and add below code


package com.test.myexample;

import java.util.Random;


import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GCMService extends GCMBaseIntentService{

public static   int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
public GCMIntentService() {
super("884643418365-pl1p16evmgcqe5ib9708qrovn728efgv");
}
 
private static final String TAG = "===GCMIntentService===";
 
 
@Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
}
 
@Override
protected void onUnregistered(Context arg0, String arg1) {
Log.i(TAG, "unregistered = "+arg1);
}
 
@Override
protected void onMessage(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
  ctx = context;
   Log.i(TAG, "new message= "+intent.getExtras().getString("message"));
   
   String message= intent.getExtras().getString("message");
   String title =intent.getExtras().getString("title");
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + intent.getExtras().toString(),title);
Log.i("onReceive","type_error");
else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED .equals(messageType)) {
sendNotification("Deleted messages on server: " + intent.getExtras().toString(),title);
Log.i("onReceive","deleted");
else {
sendNotification(message, title);
Log.i("onReceive","received:"+ intent.getExtras().toString());
}
 
Log.i("onReceive","done");
}
// Put the GCM message into a notification and post it.
private void sendNotification(String msg,String title) {
Random randomGenerator = new Random();
NOTIFICATION_ID = randomGenerator.nextInt(1000);
   mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
   PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, new Intent(ctx, GCMIntentService.class), 0);
  NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
 .setSmallIcon(R.drawable.ic_launcher2 )
 .setContentTitle(title)
 .setStyle(new NotificationCompat.BigTextStyle().bigText(msg ))
 .setContentText(msg);
  mBuilder.setContentIntent(contentIntent);
  mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
 
@Override
protected void onError(Context arg0, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
 
@Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}
}

.............................................................................................................................

Add code in AndroidManifest.xml

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
   <permission android:name="com.wired.mealio.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.wired.mealio.permission.C2D_MESSAGE" />

   Add this code inside application tree of AndroidManifest.xml.
      
       <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.test.myexample" />

</intent-filter>
 </receiver>
   <service android:name=".GCMService" />

C# Code 

Call AndroidPush function with  parament message,deviceId,title

Note: Please register your client device by GCMRegistrar  through your android project  and collect device id and save it your own database .

Necessary Reference:
using System.Net;
using System.Text;
using System.IO;



 public static string AndroidPush(string message, string deviceId, string title = "Project Title")
      {

          try
          {

               WebRequest webRequest;
                                                                                               
              var googleApikey = "AIzaSyDD0kNEqml-ToGk08RtLT0w0NNT0VjSIok";                                  
              var clientID = "884643418365-ho8n0fcn161s2p7uucmkeh727989knuf";


              webRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
              webRequest.Method = "post";
              webRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
              webRequest.Headers.Add(string.Format("Authorization: key={0}", googleApikey));
              webRequest.Headers.Add(string.Format("Sender: id={0}", clientID));

              //Data post to server                                                                                                                                      
              string postData =
               "collapse_key=score_update&time_to_live=108&delay_while_idle=1"
               +"&data.message=" + message
               + "&data.title=" + title
               +"&data.time=" + System.DateTime.Now.ToString()
               +"&registration_id=" + deviceId + "";
              Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
              webRequest.ContentLength = byteArray.Length;
              Stream dataStream = webRequest.GetRequestStream();
              dataStream.Write(byteArray, 0, byteArray.Length);
              dataStream.Close();

              WebResponse webResponse = webRequest.GetResponse();
              dataStream = webResponse.GetResponseStream();

              StreamReader streamReader = new StreamReader(dataStream);

              String responseFromServer = streamReader.ReadToEnd();
              streamReader.Close();

              dataStream.Close();
              webResponse.Close();
              return responseFromServer;
          }
          catch (Exception ex)
          {
              return ex.Message;
          }


      }

No comments:

Post a Comment