19
Home GCM Android MultiCast Push Notifications using GCM [Greeting App] About Application Search this website Select Category Categories Recent Popular Random Android GUI Tools and Kits you can’t afford to miss as an app developer Jan 15, 2015 How to Position Toast in Android Application? Jan 13, 2015 How to Receive Simple Data from Other Apps? Jan 4, 2015 How to Send Simple Data to Other Apps? Jan 4, 2015

Android MultiCast Push Notifications Using GCM [Greeting App] _ Android Tutorial

  • View
    217

  • Download
    10

Embed Size (px)

DESCRIPTION

rhrthrth

Citation preview

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 1/19

    AdvertiseHere

    Home Basics Write For Us Advertise With Us Demo Tips & Tricks About Us Other Tutorials

    Android MultiCast Push Notificationsusing GCM [Greeting App]Posted By Android Guru on Sep 23, 2014 | 18 Comments

    In the previous posts, I discussed What is GCM and how to send Push notifications using GCM service. In this post,

    I am going to develop simple Android application called Greeting App to demonstrate how to send Push

    notifications to multiple devices.

    I would recommend you to quickly take a look at the previous posts (Read: Introduction to GCM | How to send

    push notifications using GCM service?) so that you will get to know about basics of GCM.

    What is GCM?

    Google Cloud Messaging is a free service from Google which helps us to send messages (Push notifications) to

    Users device. It can also be used to send message from Users device to GCM server.

    Here is the video demo of the Application we are about to develop, watch it.

    Video Demo

    I believe you got to know about the application from video demo.

    Home GCM Android MultiCast Push Notifications using GCM [Greeting App]

    About Application

    Search this website

    SelectCategory

    Categories

    Recent Popular Random

    Android GUITools and Kitsyou cant affordto miss as an appdeveloperJan 15, 2015

    How to PositionToast in AndroidApplication?Jan 13, 2015

    How to ReceiveSimple Data fromOther Apps?Jan 4, 2015

    How to SendSimple Data toOther Apps?Jan 4, 2015

    http://programmerguru.com/advertise-with-us/http://programmerguru.com/android-tutorial/category/gcm/http://programmerguru.com/android-tutorial/introduction-to-gcm/http://programmerguru.com/about-us/http://programmerguru.com/android-tutorial/android-gui-tools-and-kits/http://programmerguru.com/android-tutorial/android-gui-tools-and-kits/https://twitter.com/AndroidGuru3http://tips.programmerguru.com/android/http://programmerguru.com/http://android-color-generator.com/http://programmerguru.com/android-tutorial/how-to-send-simple-data-to-other-apps/http://programmerguru.com/android-tutorial/how-to-receive-simple-data-from-other-apps/http://programmerguru.com/android-tutorialhttp://programmerguru.com/android-tutorial/how-to-position-toast-in-android-application/http://programmerguru.com/android-tutorial/how-to-send-simple-data-to-other-apps/http://programmerguru.com/android-tutorial/feed/https://buysellads.com/buy/detail/225182/zone/1298771?utm_source=site_225182&utm_medium=website&utm_campaign=adhere&utm_content=zone_1298771http://programmerguru.com/android-tutorial/how-to-send-push-notifications-using-gcm-service/http://www.facebook.com/AndroidProgrammerGuruhttp://programmerguru.com/android-tutorial/how-to-receive-simple-data-from-other-apps/http://programmerguru.com/android-tutorial/category/basics/http://programmerguru.com/write-for-us/http://programmerguru.com/android-tutorial/how-to-position-toast-in-android-application/http://programmerguru.com/android-tutorial/demo/https://plus.google.com/109193195162752015839http://programmerguru.com/android-tutorial/author/admin/

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 2/19

    How it works technically?

    Steps involved in sending Greeting as Push notifications:

    Developing the application involves two parts:

    1. GCM Server Application Create Web application using Php to send Greeting to User via GCM Cloud server

    2. GCM Client Application Create Android application which receive Greeting sent from GCM Server Web App

    Prerequisite

    You need to have Google Project Key, API Server Key, and GCM RegId with you in order to send and receive

    Message.

    Steps to create Google Project Key:

    It is a simple android application which shows the Greeting sent by sender.

    Once sender composed the greeting and sent it to the selected Users. Greeting will arrive in mobile devices

    of selected Users

    Buy App Source CodeFree Music ResourcesDownload Free Full BookStart DownloadDownload Full Free Books

    Send faxes with Skypepamfax.biz

    PamFax is fully integrated with Skype. Test it now!

    Free IT TrainingMashbox - API DevelopersFree PDF Converter

    You can download source code from here if you dont want to create Application from scratch, otherwise please

    proceed with below listings.

    AdvertiseHere AdvertiseHere

    AdvertiseHere AdvertiseHere

    Facebook Like Box

    AndroidProgrammerGuru

    9,787peoplelikeAndroidProgrammerGuru.

    Facebooksocialplugin

    Like

    SelectMonth

    Archives

    Blog links

    Android Home

    FromDev Web

    Development Blog

    Google Play

    Java blog

    https://play.google.com/storehttp://developer.android.com/index.htmlhttp://www.fromdev.com/https://buysellads.com/buy/detail/225182/zone/1298653?utm_source=site_225182&utm_medium=website&utm_campaign=adhere&utm_content=zone_1298653https://buysellads.com/buy/detail/225182/zone/1298653?utm_source=site_225182&utm_medium=website&utm_campaign=adhere&utm_content=zone_1298653http://javapapers.com/https://buysellads.com/buy/detail/225182/zone/1298653?utm_source=site_225182&utm_medium=website&utm_campaign=adhere&utm_content=zone_1298653https://buysellads.com/buy/detail/225182/zone/1298653?utm_source=site_225182&utm_medium=website&utm_campaign=adhere&utm_content=zone_1298653

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 3/19

    Goto https://console.developers.google.com/project and then create Project.

    Enter Project name and click create, a project will be created.

    You can see Project ID, note it down as it will be used in Step 4 of GCM Client Application.

    Steps to create API Server Key:

    Enable Google Cloud Messaging as shown below.

    https://console.developers.google.com/project

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 4/19

    Create Server Key as shown below,

    Enter your public address in order to white-list a set of IP addresses as the server key is mapped to IP addresses

    for security purpose. (Get your public IP address by googling my public ip address in Google) and click create.

    You can see SERVER_API_KEY, note it down as it will be used in Step 2 of GCM Server Application creation.

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 5/19

    You dont need to worry about creating GCM RegId, as it will be created inside Android application which we will

    discuss in some time later.

    [pglinkadssmall1]

    GCM Server Application

    I chose PHP/MySQL combo for creating API to connect and Android device to MySQL DB since the configuration

    is simple and easy and also it will be easy for you to start with.

    Step 1: Create DB and Table in MySQL

    1. Create database called db in phpMyAdmin or create it through command:

    2. Select database db in phpMyAdmin or select it through command:

    3. Create table called gcmusers in phpMyAdmin by pasting below SQL script in SQL Query box:

    Step 2: Create Php files under gcmwebapp folder under Apaches www

    config.php:

    Has configuration variable like DB Host, DB Username and DB Pasword.

    db_connect.php:

    Has methods to open and close DB connection.

    createdatabasedb

    usedb

    123456

    CREATETABLEIFNOTEXISTS`gcmusers`(`id`int(11)NOTNULLAUTO_INCREMENT,`emailid`varchar(50)NOTNULL,`gcmregid`varchar(500)NOTNULL,PRIMARYKEY(`id`))

    123456789

    123456789101112131415161718192021222324

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 6/19

    db_functions.php:

    Has methods to perform DB operations.

    insertuser.php:

    Insert Users email id and gcm reg id in DB.

    processmessage.php:

    Send greeting json to selected users.

    Download processmessage.php from here.

    viewusers.php:

    Greeting web app screen that display list of users, greeting cards etc.,

    252627282930313233

    }//Closingdatabaseconnectionpublicfunctionclose(){mysql_close();}}?>

    1234567891011121314151617181920212223242526272829303132333435363738394041424344454647

    123456789101112

    ViewUsers

    body{font:normalmedium/1.4sansserif;}div.greetblock,div.serverresponse{bordercollapse:collapse;width:60%;marginleft:auto;marginright:auto;

    http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.jshttp://programmerguru.com/android-tutorial/wp-content/uploads/2014/09/processmessage.txt

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 7/19

    131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121

    align:center;}tr>td{padding:0.25rem;textalign:center;border:1pxsolid#ccc;}tr:nthchild(even){background:#fff;}tr:nthchild(odd){background:#FA9A8B;color:#fff;}tr#header{background:#F78371;}div#norecord{margintop:10px;width:15%;marginleft:auto;marginright:auto;}input,select{cursor:pointer;}img{margintop:10px;height:200px;width:300px;}select{width:200px}div.leftdiv{width:45%;padding:010px;float:left;border:1pxsolid#ccc;margin:5px;height:320px;textalign:center;}div.rightdiv{width:45%;padding:010px;float:right;border:1pxsolid#ccc;margin:5px;height:320px;textalign:center;}hidediv{display:none;}p.header{height:40px;backgroundcolor:#EB5038;padding:10px;color:#fff;textalign:center;margin:0;marginbottom:10px;}textarea{fontsize:25px;fontweight:bold;}

    functionsendMsg(){varmsgLength=$.trim($("textarea").val()).length;varcheckedCB=$("input[type='checkbox']:checked").length;if(checkedCB==0){alert("YoumustselectatleastoneUsertosendmessage");}elseif(msgLength==0){alert("Youleftthemessagefieldblank,pleasefillit");}else{varformData=$(".wrapper").find("input").serialize()+"&imgurl="+$("#festival"$.ajax({type:"POST",data:formData,url:"processmessage.php",success:function(res){$(".greetblock").slideUp(1000);$(".serverresponse").prepend(res).hide().fadeIn(2000);}});}}$(function(){$(".serverresponse").hide()$("input[type='checkbox']").click(function(){if($(this).is(':checked')){$(this).parent().css("border","3pxsolidred");}else{$(this).parent().css("border","0px");}});$("div.leftdiv,div.rightdiv").hover(function(){$(this).css("background","#FAFAFA");},function(){$(this).css("background","#fff");});$("#festival").change(function(){$("img").attr("src",$(this).val());});$("#sendmsg").click(function(){

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 8/19

    Step 3: Update API Server Key

    Update API_SERVER_KEY in function sendMessageThroughGCM present in processmessage.php with the one

    you created.

    GCM Client Application

    Step 1: Create Android Application Project

    Step 2: Add library to project

    Add below third party library into projects libs folder. You can also download it if you dont have it with you.

    1. Android Asynchronous Http Client An asynchronous callback-based Http client for Android built on top of

    122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197

    $(".serverresponse").fadeOut(300,function(){$(".greetblock").fadeIn(1000);});});});

    SelectUserstowhomyouwanttosendGreetingmessage

    IdEmailIdSendMessage?

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 9/19

    Apaches HttpClient libraries which is used by Pinterest, Instagram etc.,. Download

    Step 3: Setup Google Play Services library project

    To write GCM client application, we need to use the GoogleCloudMessaging API. To use this API, we must set up

    the project to use the Google Play services SDK.

    Take help from here to setup Google Play Service library project.

    Step 4: Design Screens

    We are going to have two activities:

    MainActivity Launch Screen of the Application

    GreetingActivity Greeting Screen of the Application

    Before creating the layouts, make sure below resources are added.

    Add string resources to strings.xml present under /res/values folder.

    strings.xml

    Add dimension resource to dimens.xml present under /res/values folder.

    dimens.xml

    Add color resources to colors.xml present under /res/values folder.

    colors.xml

    Create bg_button_rounded.xml under /res/drawable-mdpi folder and add below code to it.

    bg_button_rounded.xml

    Create bg_form_rounded.xml under /res/drawable-mdpi folder and add below code to it.

    bg_form_rounded.xml

    123456789101112131415

    GCMGreetingAppHelloworld!SettingsGCMGreetingAppEmailAddressRegisterMeDon\'thaveaccount?SignUpMessagesentbyserverwillappearhere.MessageHelloUser

    1234567

    16dp16dp

    12345678

    #ffffff#000000#EB5038#CA3822#A92815

    123456789101112131415161718192021222324

    12345

    https://developer.android.com/google/play-services/setup.html#Setuphttp://schemas.android.com/apk/res/androidhttps://github.com/loopj/android-async-http/raw/master/releases/android-async-http-1.4.4.jarhttp://schemas.android.com/apk/res/android

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 10/19

    Create bg_gradient.xml under /res/drawable-mdpi folder and add below code to it.

    bg_gradient.xml

    Create two layout XMLs under /res/layout folder:

    activity_main.xml

    Launch Screen

    activity_greeting.xml

    Greeting Screen

    6789101112131415161718192021222324

    12345678910

    1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556

    1234

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 11/19

    Step 5: ApplicationConstants.java

    We are done with Layout designing, let us jump into Coding.

    Create ApplicationConstants.Java under the package com.prgguru.example and fill it with below code. It has

    constants used across application. Make sure your updated Google_Project_Key with the one you created above.

    Step 6: Utility.java

    Create Utility.Java under the package com.prgguru.example and fill it with below code. It has Utility methods.

    567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253

    android:background="@drawable/bg_gradient"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".GreetingActivity">

    Make sure you changed the IP address mentioned in the APP_SERVER_URL constant with your Machine/LAN IP

    address.

    123456789101112

    packagecom.prgguru.example;publicinterfaceApplicationConstants{//PhpApplicationURLtostoreRegIDcreatedstaticfinalStringAPP_SERVER_URL="http://192.168.2.4:9000/gcmwebapp/insertuser.php//GoogleProjectNumberstaticfinalStringGOOGLE_PROJ_ID="837715578074";staticfinalStringMSG_KEY="m";}

    12345678910111213141516171819202122232425

    packagecom.prgguru.example;importjava.util.regex.Matcher;importjava.util.regex.Pattern;/***ClasswhichhasUtilitymethods**/publicclassUtility{privatestaticPatternpattern;privatestaticMatchermatcher;//EmailPatternprivatestaticfinalStringEMAIL_PATTERN="^[_AZaz09\\+]+(\\.[_AZaz09]+)*@"+"[AZaz09]+(\\.[AZaz09]+)*(\\.[AZaz]{2,})$";/***ValidateEmailwithregularexpression**@paramemail*@returntrueforValidEmailandfalseforInvalidEmail*/publicstaticbooleanvalidate(Stringemail){pattern=Pattern.compile(EMAIL_PATTERN);matcher=pattern.matcher(email);

    DEVELOPERHighlight

    DEVELOPERHighlight

    http://192.168.2.4:9000/gcmwebapp/insertuser.php

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 12/19

    Step 7: MainActivity.java

    Create MainActivity.Java under the package com.prgguru.example and fill it with below code.

    It is the launch screen activity which asks User to enter Email ID, once Email ID is submitted Application will try to

    register Users device in Google Cloud Messaging server. Registration Id will be generated once the registration is

    successfully completed.

    Registration Id will be stored in GCM Server Application (created above) as text file (GCMRegId.txt).

    262728

    returnmatcher.matches();}}

    123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293

    packagecom.prgguru.example;importjava.io.IOException;importandroid.app.Activity;importandroid.app.ProgressDialog;importandroid.content.Context;importandroid.content.Intent;importandroid.content.SharedPreferences;importandroid.os.AsyncTask;importandroid.os.Bundle;importandroid.text.TextUtils;importandroid.view.View;importandroid.widget.EditText;importandroid.widget.Toast;importcom.google.android.gms.common.ConnectionResult;importcom.google.android.gms.common.GooglePlayServicesUtil;importcom.google.android.gms.gcm.GoogleCloudMessaging;importcom.loopj.android.http.AsyncHttpClient;importcom.loopj.android.http.AsyncHttpResponseHandler;importcom.loopj.android.http.RequestParams;publicclassMainActivityextendsActivity{ProgressDialogprgDialog;RequestParamsparams=newRequestParams();GoogleCloudMessaginggcmObj;ContextapplicationContext;StringregId="";privatefinalstaticintPLAY_SERVICES_RESOLUTION_REQUEST=9000;AsyncTaskcreateRegIdTask;publicstaticfinalStringREG_ID="regId";publicstaticfinalStringEMAIL_ID="eMailId";EditTextemailET;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);applicationContext=getApplicationContext();emailET=(EditText)findViewById(R.id.email);prgDialog=newProgressDialog(this);//SetProgressDialogTextprgDialog.setMessage("Pleasewait...");//SetCancelableasFalseprgDialog.setCancelable(false);SharedPreferencesprefs=getSharedPreferences("UserDetails",Context.MODE_PRIVATE);StringregistrationId=prefs.getString(REG_ID,"");if(!TextUtils.isEmpty(registrationId)){Intenti=newIntent(applicationContext,GreetingActivity.class);i.putExtra("regId",registrationId);startActivity(i);finish();}}//WhenRegisterMebuttonisclickedpublicvoidRegisterUser(Viewview){StringemailID=emailET.getText().toString();if(!TextUtils.isEmpty(emailID)&&Utility.validate(emailID)){//CheckifGooglePlayServiceisinstalledinDevice//PlayservicesisneededtohandleGCMstuffsif(checkPlayServices()){//RegisterDeviceinGCMServerregisterInBackground(emailID);}}//WhenEmailisinvalidelse{Toast.makeText(applicationContext,"Pleaseentervalidemail",Toast.LENGTH_LONG).show();}}//AsyncTasktoregisterDeviceinGCMServerprivatevoidregisterInBackground(finalStringemailID){newAsyncTask(){@OverrideprotectedStringdoInBackground(Void...params){Stringmsg="";try{if(gcmObj==null){

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 13/19

    949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202

    gcmObj=GoogleCloudMessaging.getInstance(applicationContext);}regId=gcmObj.register(ApplicationConstants.GOOGLE_PROJ_ID);msg="RegistrationID:"+regId;}catch(IOExceptionex){msg="Error:"+ex.getMessage();}returnmsg;}@OverrideprotectedvoidonPostExecute(Stringmsg){if(!TextUtils.isEmpty(regId)){storeRegIdinSharedPref(applicationContext,regId,emailID);Toast.makeText(applicationContext,"RegisteredwithGCMServersuccessfully.\n\n"+msg,Toast.LENGTH_SHORT).show();}else{Toast.makeText(applicationContext,"RegIDCreationFailed.\n\nEitheryouhaven'tenabledInternetorGCMserverisbusyrightnow.MakesureyouenabledInternetandtryregisteringagainaftersometime."+msg,Toast.LENGTH_LONG).show();}}}.execute(null,null,null);}//StoreRegIdandEmailenteredbyUserinSharedPrefprivatevoidstoreRegIdinSharedPref(Contextcontext,StringregId,StringemailID){SharedPreferencesprefs=getSharedPreferences("UserDetails",Context.MODE_PRIVATE);SharedPreferences.Editoreditor=prefs.edit();editor.putString(REG_ID,regId);editor.putString(EMAIL_ID,emailID);editor.commit();storeRegIdinServer(regId,emailID);}//ShareRegIDandEmailIDwithGCMServerApplication(Php)privatevoidstoreRegIdinServer(StringregId2,StringemailID){prgDialog.show();params.put("emailId",emailID);params.put("regId",regId);System.out.println("Emailid="+emailID+"RegId="+regId);//MakeRESTfulwebservicecallusingAsyncHttpClientobjectAsyncHttpClientclient=newAsyncHttpClient();client.post(ApplicationConstants.APP_SERVER_URL,params,newAsyncHttpResponseHandler(){//WhentheresponsereturnedbyRESThasHttp//responsecode'200'@OverridepublicvoidonSuccess(Stringresponse){//HideProgressDialogprgDialog.hide();if(prgDialog!=null){prgDialog.dismiss();}Toast.makeText(applicationContext,"RegIdsharedsuccessfullywithWebApp",Toast.LENGTH_LONG).show();Intenti=newIntent(applicationContext,GreetingActivity.class);i.putExtra("regId",regId);startActivity(i);finish();}//WhentheresponsereturnedbyRESThasHttp//responsecodeotherthan'200'suchas'404',//'500'or'403'etc@OverridepublicvoidonFailure(intstatusCode,Throwableerror,Stringcontent){//HideProgressDialogprgDialog.hide();if(prgDialog!=null){prgDialog.dismiss();}//WhenHttpresponsecodeis'404'if(statusCode==404){Toast.makeText(applicationContext,"Requestedresourcenotfound",Toast.LENGTH_LONG).show();}//WhenHttpresponsecodeis'500'elseif(statusCode==500){Toast.makeText(applicationContext,"Somethingwentwrongatserverend",Toast.LENGTH_LONG).show();}//WhenHttpresponsecodeotherthan404,500else{Toast.makeText(applicationContext,"UnexpectedErrorocccured![MostcommonError:Devicemight"+"notbeconnectedtoInternetorremoteserverisnotupandrunning],checkforothererrorsaswell"Toast.LENGTH_LONG).show();}}});}//CheckifGooglePlayservicesisinstalledinDeviceornot

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 14/19

    Step 8: GreetingActivity.java

    Create GreetingActivity.Java under the package com.prgguru.example and fill it with below code.

    It is the Greeting screen activity which display the message sent from GCM Server Application.

    203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236

    privatebooleancheckPlayServices(){intresultCode=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);//WhenPlayservicesnotfoundindeviceif(resultCode!=ConnectionResult.SUCCESS){if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){//ShowErrordialogtoinstallPlayservicesGooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RESOLUTION_REQUEST).show();}else{Toast.makeText(applicationContext,"Thisdevicedoesn'tsupportPlayservices,Appwillnotworknormally"Toast.LENGTH_LONG).show();finish();}returnfalse;}else{Toast.makeText(applicationContext,"ThisdevicesupportsPlayservices,Appwillworknormally",Toast.LENGTH_LONG).show();}returntrue;}//WhenApplicationisresumed,checkforPlayservicessupporttomakesure//appwillberunningnormally@OverrideprotectedvoidonResume(){super.onResume();checkPlayServices();}}

    1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465

    packagecom.prgguru.example;importorg.json.JSONException;importorg.json.JSONObject;importandroid.app.Activity;importandroid.app.ProgressDialog;importandroid.content.Context;importandroid.content.SharedPreferences;importandroid.os.Bundle;importandroid.widget.TextView;importandroid.widget.Toast;importcom.androidquery.AQuery;importcom.google.android.gms.common.ConnectionResult;importcom.google.android.gms.common.GooglePlayServicesUtil;publicclassGreetingActivityextendsActivity{TextViewemailET;privateAQueryaq;//ProgressDialogbarobjectProgressDialogprgDialog;privatefinalstaticintPLAY_SERVICES_RESOLUTION_REQUEST=9000;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_test);aq=newAQuery(this);Stringjson=getIntent().getStringExtra("greetjson");SharedPreferencesprefs=getSharedPreferences("UserDetails",Context.MODE_PRIVATE);emailET=(TextView)findViewById(R.id.greetingmsg);//CheckifGooglePlayServiceisinstalledinDevice//PlayservicesisneededtohandleGCMstuffsif(!checkPlayServices()){Toast.makeText(getApplicationContext(),"Thisdevicedoesn'tsupportPlayservices,Appwillnotworknormally"Toast.LENGTH_LONG).show();}//Whenjsonisnotnullif(json!=null){try{JSONObjectjsonObj=newJSONObject(json);SharedPreferences.Editoreditor=prefs.edit();editor.putString("greetimgurl",jsonObj.getString("greetImgURL"));editor.putString("greetmsg",jsonObj.getString("greetMsg"));editor.commit();emailET.setText(prefs.getString("greetmsg",""));//RenderImagereadfromImageURLusingaquery'image'methodaq.id(R.id.greetimg).progress(R.id.progress).image(prefs.getString("greetimgurl",""),true,true,0,0,null,AQuery.FADE_IN);}catch(JSONExceptione){//TODOAutogeneratedcatchblocke.printStackTrace();}}//WhenJsonisnull

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 15/19

    Step 9: GcmBroadcastReceiver.java

    Create GcmBroadcastReceiver.Java under the package com.prgguru.example and fill it with below code.

    A broadcast receiver is the mechanism GCM uses to deliver messages. When message is sent through GCM

    Server application, it triggers the broadcast receivers onReceive() method, which has the responsibility of making

    sure that the GCM message gets handled.

    A WakefulBroadcastReceiver is a special type of broadcast receiver that takes care of creating and managing a

    partial wake lock for your app.

    Step 10: GCMNotificationIntentService.java

    Create GcmBroadcastReceiver.Java under the package com.prgguru.example and fill it with below code.

    The intent service shown below does the actual work of handling the GCM message. This class processes the

    GCM message based on message type, and posts the result in a notification.

    66676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109

    elseif(!"".equals(prefs.getString("greetimgurl",""))&&!"".equals(prefs.getString(emailET.setText(prefs.getString("greetmsg",""));aq.id(R.id.greetimg).progress(R.id.progress).image(prefs.getString("greetimgurl",""),true,true,0,0,null,AQuery.FADE_IN);}}//CheckifGooglePlayservicesisinstalledinDeviceornotprivatebooleancheckPlayServices(){intresultCode=GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);//WhenPlayservicesnotfoundindeviceif(resultCode!=ConnectionResult.SUCCESS){if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){//ShowErrordialogtoinstallPlayservicesGooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RESOLUTION_REQUEST).show();}else{Toast.makeText(getApplicationContext(),"Thisdevicedoesn'tsupportPlayservices,Appwillnotworknormally"Toast.LENGTH_LONG).show();finish();}returnfalse;}else{Toast.makeText(getApplicationContext(),"ThisdevicesupportsPlayservices,Appwillworknormally",Toast.LENGTH_LONG).show();}returntrue;}//WhenApplicationisresumed,checkforPlayservicessupporttomakesure//appwillberunningnormally@OverrideprotectedvoidonResume(){super.onResume();checkPlayServices();}}

    123456789101112131415161718

    packagecom.prgguru.example;importandroid.app.Activity;importandroid.content.ComponentName;importandroid.content.Context;importandroid.content.Intent;importandroid.support.v4.content.WakefulBroadcastReceiver;publicclassGcmBroadcastReceiverextendsWakefulBroadcastReceiver{@OverridepublicvoidonReceive(Contextcontext,Intentintent){ComponentNamecomp=newComponentName(context.getPackageName(),GCMNotificationIntentService.class.getName());startWakefulService(context,(intent.setComponent(comp)));setResultCode(Activity.RESULT_OK);}}

    123456789101112131415161718192021

    packagecom.prgguru.example;importandroid.app.IntentService;importandroid.app.Notification;importandroid.app.NotificationManager;importandroid.app.PendingIntent;importandroid.content.Context;importandroid.content.Intent;importandroid.os.Bundle;importandroid.support.v4.app.NotificationCompat;importcom.google.android.gms.gcm.GoogleCloudMessaging;publicclassGCMNotificationIntentServiceextendsIntentService{//SetsanIDforthenotification,soitcanbeupdatedpublicstaticfinalintnotifyID=9001;NotificationCompat.Builderbuilder;publicGCMNotificationIntentService(){super("GcmIntentService");}

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 16/19

    Demo

    Thats all. Its time to test our code.

    Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >>

    Choose emulator or device.

    Download Source Code

    [pglinkadssmall]

    If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by

    sharing the article in Facebook or Twitter.

    Tweet

    4

    You are always welcome to provide your comments and feedback from 18 Comments box.

    Reference

    2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283

    publicstaticfinalStringTAG="GCMNotificationIntentService";@OverrideprotectedvoidonHandleIntent(Intentintent){Bundleextras=intent.getExtras();GoogleCloudMessaginggcm=GoogleCloudMessaging.getInstance(this);StringmessageType=gcm.getMessageType(intent);if(!extras.isEmpty()){if(GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)){sendNotification("Senderror:"+extras.toString());}elseif(GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)){sendNotification("Deletedmessagesonserver:"+extras.toString());}elseif(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)){sendNotification(""+extras.get(ApplicationConstants.MSG_KEY));//WhenMessageisreceivednormallyfromGCMCloudServer}}GcmBroadcastReceiver.completeWakefulIntent(intent);}privatevoidsendNotification(StringgreetMsg){IntentresultIntent=newIntent(this,GreetingActivity.class);resultIntent.putExtra("greetjson",greetMsg);resultIntent.setAction(Intent.ACTION_MAIN);resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);PendingIntentresultPendingIntent=PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_ONE_SHOT);NotificationCompat.BuildermNotifyBuilder;NotificationManagermNotificationManager;mNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);mNotifyBuilder=newNotificationCompat.Builder(this).setContentTitle("Alert").setContentText("You'vereceivednewmessages.").setSmallIcon(R.drawable.ic_launcher);//SetpendingintentmNotifyBuilder.setContentIntent(resultPendingIntent);//SetVibrate,SoundandLightintdefaults=0;defaults=defaults|Notification.DEFAULT_LIGHTS;defaults=defaults|Notification.DEFAULT_VIBRATE;defaults=defaults|Notification.DEFAULT_SOUND;mNotifyBuilder.setDefaults(defaults);//SetthecontentforNotificationmNotifyBuilder.setContentText("NewmessagefromServer");//SetautocancelmNotifyBuilder.setAutoCancel(true);//PostanotificationmNotificationManager.notify(notifyID,mNotifyBuilder.build());}}

    Entire project is zipped and is available for download. Unzip the downloaded project and to import the project

    into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in

    eclipse).

    *apk in Android is the installation file similar to exe in windows.

    Download Source Code

    18Share

    http://programmerguru.com/android-tutorial/how-to-import-android-project-in-eclipse/http://programmerguru.com/verify-user?tutorial=Android&download_file=GCMGreetingApp

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 17/19

    Share This Post On

    Android GCM

    [pgwriteforus]

    [pgfeedback]

    18Comments ProgrammerGuruTutorialBlog Login

    SortbyNewest Share

    Jointhediscussion

    Reply

    Jigar amonthago

    Thankyousomuchforthistutorial!!Goodgoing!YOUareAWESOME!:)^_^

    Reply

    AndroidGuru amonthagoMod >Jigar

    Thanksyou.

    Reply

    FrancescoFerigo 2monthsago

    Manymanythanks

    Reply

    AndroidGuru 2monthsagoMod >FrancescoFerigo

    Youarewelcome.

    Reply

    Ray 2monthsago

    HI,I'MHAVINGPROBLEMSWITHTHAT

    AsyncHttpClientclient=newAsyncHttpClient()

    client.post(ApplicationConstants.APP_SERVER_URL,params,

    newAsyncHttpResponseHandler(){

    //WhentheresponsereturnedbyRESThasHttp

    //responsecode'200'

    @Override

    Reply

    AndroidGuru 2monthsagoMod >Ray

    YouneedtouseyourserverURL.1

    Reply

    joe 3monthsago

    GreatJobonthetutorial..butiamhavingsometroublewiththeapp..Irantheappandtheserver..butwheniruntheappittellsme"Thisappwon'trununlessyouupdategoogleplayservices"?iamrunningaemulator..

    thankyou.

    Reply

    AndroidGuru 2monthsagoMod >joe

    GooglePlayServiceisneededforinvokingGCMservice.ItistheprecheckIamdoingincode.

    Reply

    abul 3monthsago

    "Youarealwayswelcometoprovideyourcommentsandfeedbackfromcommentbox."

    I'dtrytodiscussaboutthisproject,butmyquestionshaveneverbeenapproved.ckckck

    AndroidGuru 2monthsagoMod >abul

    HIAbul,

    IamnotfulltimebloggersowhenIgettimeIwritetutorialsandalsoapprovecomments.Youcanseeyourquestionstoday.:)

    Favorite

    Share

    Share

    Share

    Share

    Share

    Share

    Share

    Share

    Share

    Author: Android Guru

    https://plus.google.com/share?url=http://programmerguru.com/android-tutorial/android-multicast-push-notifications-using-gcm/https://developer.android.com/google/gcm/index.htmlhttp://www.facebook.com/sharer/sharer.php?s=100&p[url]=http://programmerguru.com/android-tutorial/android-multicast-push-notifications-using-gcm/&p[images][0]=&p[title]=Android%20MultiCast%20Push%20Notifications%20using%20GCM%20[Greeting%20App]https://twitter.com/intent/tweet?url=http://programmerguru.com/android-tutorial/android-multicast-push-notifications-using-gcm/&text=Android%20MultiCast%20Push%20Notifications%20using%20GCM%20[Greeting%20App]http://programmerguru.com/android-tutorial

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 18/19

    Recent Posts Recent Comments Tags

    Action Bar Activity AJAX android

    apps development AndroidBasics android developmentcompany Android Wear ApplicationAQuery AsyncTask AuthenticationBroadcast receivers Button Call CameraDot Net Web Service Eclipse EmailFacebook Gallery GCM ImageImage_Upload Intent Java WebService jQuery jQuery Mobile JSONLayout Library LocalizationMedia Notifications php Restfulwebservice SD Card Seek bar SQLiteText to speech Vibrate Video videos webWeb service Webview

    HowtoaddFacebooklikebuttoninAndroidapplications?4comments3monthsago

    sugatHi,Itiredyoursampleproject,itdoesnotwork.IsitbeacuseofFBapproval?oramImissingsomething?

    HowtopoststatusupdateorsharelinkinFacebookfromAndroidApplication?2comments2monthsago

    AndroidGuruAppwillstopworking.ItisbettertocheckiffacebookappisinstalledalreadyinAndroiddevice.

    HowtosyncRemoteMySQLDBtoSQLiteonAndroid?76comments7monthsago

    AsadAlibrohowdidusolvedit,,,ihavethesameproblem..helpmetheniwillworkonhavingbothmysqlandsqlitesynchronized...

    Howtopickimagefromgallery?1comment4monthsago

    MeHowcanIstorethisimage,soIcanseeitagainwhenopeningtheappagain?

    ALSOONPROGRAMMERGURUTUTORIALBLOG

    Reply

    Reply

    abul 3monthsago

    whyigotfailure?wherecaniseetheerror?1

    Reply

    AndroidGuru 2monthsagoMod >abul

    Pleaseseetheerrorinlogcat.

    Reply

    joe 3monthsago

    Ihavesuccessfullycreatedandrantheapp,butwheniopenedtheappandtrytoregister..itcreatedtheregisteridbutthengivesmeanerror

    UnexpectedErrorOcccured~[MostCommonError:Devicenotbeconnectedtointernetorremoteserverisnotupandrunning,checkothererrorsaswell.

    Iamrunningxampponlocalhost.

    pleasehelp..thankyou

    Reply

    AndroidGuru 2monthsagoMod >joe

    DidyouchangetheIPaddressinJavafiletoyourLANIPaddress?

    Reply

    abul 3monthsago

    i'dsuccessrunthisproject,i'dsendmessagesuccessfullybutsuddenlyigotfail:{"multicast_id":....,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}.ihavetoreinstalltheapplicationordeletemydevice'sdatafromtheDBandreregistersoIcansendmessagessuccessfullyagain.Itoccuredrepeatly.whydidithappen?andhowcanichecktheerrorthatmakemegotfailedtosendmessage?

    3

    Reply

    RahulChauhan 4monthsago

    Nicepostbuddy.

    Reply

    MonowarHossain 4monthsago

    Wow!VeryNicepostandalsohelpful.Iamreallysurprisedtoreadthispost.IknowhereaboutGCM.NicepostBOSS!!!

    Reply

    AndroidGuru 4monthsagoMod >MonowarHossain

    Thankyou.1

    WHAT'STHIS?

    Subscribe AddDisqustoyoursited Privacy

    Share

    Share

    Share

    Share

    Share

    Share

    Share

    Share

    Share

    Android GUI Tools and Kits

    you cant afford to miss as an

    app developer

    How to Position Toast in

    Android Application?

    How to Receive Simple Data

    from Other Apps?

    Android Guru on Android

    Java Web Service Login

    Android Guru on Introduction

    to GCM

    Android Guru on How to send

    push notifications using GCM

    service?

    http://programmerguru.com/android-tutorial/tag/action-bar/http://programmerguru.com/android-tutorial/android-java-web-service-login/#comment-57297http://programmerguru.com/android-tutorial/tag/jquery/http://programmerguru.com/http://programmerguru.com/android-tutorial/tag/android-apps-development/http://programmerguru.com/android-tutorial/tag/web-service-2/http://programmerguru.com/android-tutorial/tag/vibrate/http://programmerguru.com/android-tutorial/android-gui-tools-and-kits/http://programmerguru.com/android-tutorial/tag/seek-bar/http://programmerguru.com/android-tutorial/tag/sqlite/http://programmerguru.com/android-tutorial/tag/android-development-company/http://programmerguru.com/android-tutorial/how-to-send-push-notifications-using-gcm-service/#comment-57295http://programmerguru.com/android-tutorial/tag/java-web-service/http://programmerguru.com/android-tutorial/tag/facebook/http://programmerguru.com/android-tutorial/tag/dot-net-web-service/http://programmerguru.com/http://programmerguru.com/android-tutorial/how-to-position-toast-in-android-application/http://programmerguru.com/android-tutorial/tag/eclipse/http://programmerguru.com/android-tutorial/introduction-to-gcm/#comment-57296http://programmerguru.com/android-tutorial/tag/web/http://programmerguru.com/android-tutorial/tag/webview/http://programmerguru.com/android-tutorial/tag/php/http://programmerguru.com/android-tutorial/advertise-with-us/http://programmerguru.com/android-tutorial/tag/call/http://programmerguru.com/android-tutorial/tag/broadcast-receivers/http://programmerguru.com/android-tutorial/tag/asynctask/http://programmerguru.com/http://programmerguru.com/android-tutorial/how-to-receive-simple-data-from-other-apps/http://programmerguru.com/android-tutorial/tag/notifications/http://programmerguru.com/android-tutorial/tag/button/http://programmerguru.com/android-tutorial/tag/image/http://programmerguru.com/android-tutorial/tag/library/http://programmerguru.com/android-tutorial/tag/layout/http://programmerguru.com/android-tutorial/tag/sd-card/http://programmerguru.com/android-tutorial/tag/camera/http://programmerguru.com/android-tutorial/tag/android-wear/http://programmerguru.com/android-tutorial/tag/video/http://programmerguru.com/android-tutorial/tag/activity/http://programmerguru.com/android-tutorial/tag/gallery/http://programmerguru.com/android-tutorial/tag/jquery-mobile/http://programmerguru.com/android-tutorial/tag/gcm/http://programmerguru.com/android-tutorial/tag/aquery/http://programmerguru.com/android-tutorial/tag/restful-webservice/http://programmerguru.com/android-tutorial/tag/image_upload/http://programmerguru.com/android-tutorial/tag/application/http://programmerguru.com/android-tutorial/tag/localization/http://programmerguru.com/android-tutorial/tag/android-basics/http://programmerguru.com/android-tutorial/tag/ajax/http://programmerguru.com/android-tutorial/tag/email/http://programmerguru.com/android-tutorial/tag/authentication/http://programmerguru.com/android-tutorial/tag/text-to-speech-2/http://programmerguru.com/android-tutorial/tag/videos-2/http://programmerguru.com/android-tutorial/tag/json/http://programmerguru.com/android-tutorial/tag/media/http://programmerguru.com/android-tutorial/tag/intent/

  • // AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial

    http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/ 19/19