Escolar Documentos
Profissional Documentos
Cultura Documentos
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
AdvertiseHere
Home
Home
Basics
Write For Us
GCM
Advertise With Us
Demo
About Us
Other Tutorials
Categories
SelectCategory
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
Recent
Popular
Random
Android GUI
Tools and Kits
you cant 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
I believe you got to know about the application from video demo.
About Application
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
1/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
AdvertiseHere
AdvertiseHere
AdvertiseHere
AdvertiseHere
Free IT Training
Mashbox - API Developers
Free PDF Converter
How it works technically?
AndroidProgrammerGuru
Like
9,787peoplelikeAndroidProgrammerGuru.
Facebooksocialplugin
Archives
SelectMonth
Blog links
Android Home
FromDev Web
Development Blog
You can download source code from here if you dont want to create Application from scratch, otherwise please
proceed with below listings.
Google Play
Java blog
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:
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
2/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
You can see Project ID, note it down as it will be used in Step 4 of GCM Client Application.
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
3/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
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.
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
4/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
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]
CREATETABLEIFNOTEXISTS`gcmusers`(
`id`int(11)NOTNULLAUTO_INCREMENT,
`emailid`varchar(50)NOTNULL,
`gcmregid`varchar(500)NOTNULL,
PRIMARYKEY(`id`)
)
Step 2: Create Php files under gcmwebapp folder under Apaches www
config.php:
Has configuration variable like DB Host, DB Username and DB Pasword.
1
2
3
4
5
6
7
8
9
<?php
/**
*DBconfigurationvariables
*/
define("DB_HOST","localhost");
define("DB_USER","UserName");
define("DB_PASSWORD","PWD");
define("DB_DATABASE","db");
?>
db_connect.php:
Has methods to open and close DB connection.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
classDB_Connect{
//constructor
function__construct(){
//destructor
function__destruct(){
//$this>close();
}
//Connectingtodatabase
publicfunctionconnect(){
require_once'config.php';
//connectingtomysql
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
//selectingdatabase
mysql_select_db(DB_DATABASE);
//returndatabasehandler
return$con;
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
5/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
25
26
27
28
29
30
31
32
33
//Closingdatabaseconnection
publicfunctionclose(){
mysql_close();
}
}
?>
db_functions.php:
Has methods to perform DB operations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
classDB_Functions{
private$db;
function__construct(){
include_once'./db_connect.php';
//Connecttodatabase
$this>db=newDB_Connect();
$this>db>connect();
}
//destructor
function__destruct(){
}
/**
*Insertnewuser
*
*/
publicfunctioninsertUser($emailId,$gcmRegId){
//Insertuserintodatabase
$result=mysql_query("INSERTINTOgcmusers(emailid,gcmregid)VALUES('$emailId','$gcmRegId')"
if($result){
returntrue;
}else{
returnfalse;
}
}
/**
*Selectalluser
*
*/
publicfunctiongetAllUsers(){
$result=mysql_query("select*FROMgcmusers");
return$result;
}
/**
*GetGCMRegId
*
*/
publicfunctiongetGCMRegID($emailID){
$result=mysql_query("SELECTgcmregidFROMgcmusersWHEREemailid="."'$emailID'"
return$result;
}
}
?>
insertuser.php:
Insert Users email id and gcm reg id in DB.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
include_once'./db_functions.php';
//CreateObjectforDB_Functionsclas
$db=newDB_Functions();
$emailID=$_POST["emailId"];
$regId=$_POST["regId"];
$res=$db>insertUser($emailID,$regId);
echo"EmailId".$emailID."RegId".$regId;
if($res){
echo"GCMRegIdbasbeensharedsuccessfullywithServer";
}else{
echo"ErroroccuredwhilesharingGCMRegIdwithServerwebapp";
}
?>
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.,
1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head><title>ViewUsers</title>
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
body{
font:normalmedium/1.4sansserif;
}
div.greetblock,div.serverresponse{
bordercollapse:collapse;
width:60%;
marginleft:auto;
marginright:auto;
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
6/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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;
}
</style>
<script>
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(){
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
7/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
$(".serverresponse").fadeOut(300,function(){
$(".greetblock").fadeIn(1000);
});
});
});
</script>
</head>
<body>
<?php
include_once'db_functions.php';
$db=newDB_Functions();
$users=$db>getAllUsers();
if($users!=false)
$no_of_users=mysql_num_rows($users);
else
$no_of_users=0;
?>
<?php
if($no_of_users>0){
?>
<divclass="greetblock">
<divclass="leftdiv">
<pclass="header">SelectUserstowhomyouwanttosendGreetingmessage
</p>
<table>
<trid="header"><td>Id</td><td>EmailId</td><td>SendMessage?</td></tr>
<?php
while($row=mysql_fetch_array($users)){
?>
<tr>
<td><span><?phpecho$row["id"]?></span></td>
<td><span><?phpecho$row["emailid"]?></span></td>
<td><spanclass="wrapper"><inputtype="checkbox"name="sendmsg[]"value="<?phpecho$row["
</tr>
<?php}?>
</table>
</div>
<divclass="rightdiv">
<pclass="header">SelectGreetingCard
</p>
<selectid="festival">
<optionvalue="http://192.168.2.4:9000/gcmwebapp/img/diwali.png">Diwali</option>
<optionvalue="http://192.168.2.4:9000/gcmwebapp/img/pongal.png">Pongal</option>
<optionvalue="http://192.168.2.4:9000/gcmwebapp/img/christmas.png">Christmas</option>
<optionvalue="http://192.168.2.4:9000/gcmwebapp/img/ramzan.png">Ramadan</option>
</select>
<br/>
<imgsrc="http://192.168.2.4:9000/gcmwebapp/img/diwali.png"/>
</div>
<divclass="leftdiv">
<pclass="header">Typeyourmessage
</p>
<textareacols="15"rows="5"value="txtarea">
</textarea>
</div>
<divclass="rightdiv">
<pclass="header">SendyourcustomizedmessagetoyourUsers
</p>
<center>
<buttononclick="sendMsg()">SendMessage</button>
</center>
</div>
</div>
<divclass="serverresponsehidediv">
<center><buttonid="sendmsg">SendMessageAgain</button></center>
</div>
<?php}else{?>
<divid="norecord">
NorecordsinMySQLDB
</div>
<?php}?>
</body>
</html>
8/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
<?xmlversion="1.0"encoding="utf8"?>
<resources>
<stringname="app_name">GCMGreetingApp</string>
<stringname="hello_world">Helloworld!</string>
<stringname="action_settings">Settings</string>
<stringname="welcome">GCMGreetingApp</string>
<stringname="email">EmailAddress</string>
<stringname="login">RegisterMe</string>
<stringname="signup">Don\'thaveaccount?SignUp</string>
<stringname="defaultmsg">Messagesentbyserverwillappearhere.</string>
<stringname="msg_title">Message</string>
<stringname="user_title">HelloUser</string>
</resources>
<resources>
<!Defaultscreenmargins,pertheAndroidDesignguidelines.>
<dimenname="activity_horizontal_margin">16dp</dimen>
<dimenname="activity_vertical_margin">16dp</dimen>
</resources>
<?xmlversion="1.0"encoding="utf8"?>
<resources>
<colorname="white">#ffffff</color>
<colorname="black">#000000</color>
<colorname="bg_gradient_start">#EB5038</color>
<colorname="bg_gradient_end">#CA3822</color>
<colorname="bg_button_login">#A92815</color>
</resources>
Create bg_button_rounded.xml under /res/drawable-mdpi folder and add below code to it.
bg_button_rounded.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xmlversion="1.0"encoding="utf8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!Backgroundcolor>
<solid
android:color="@color/bg_button_login">
</solid>
<!Padding>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp">
</padding>
<!Cornerradius>
<corners
android:radius="6dp">
</corners>
</shape>
Create bg_form_rounded.xml under /res/drawable-mdpi folder and add below code to it.
bg_form_rounded.xml
1
2
3
4
5
<?xmlversion="1.0"encoding="utf8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
9/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!Backgroundcolor>
<solid
android:color="@color/white">
</solid>
<!Padding>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp">
</padding>
<!Cornerradius>
<corners
android:radius="6dp">
</corners>
</shape>
Create bg_gradient.xml under /res/drawable-mdpi folder and add below code to it.
bg_gradient.xml
1
2
3
4
5
6
7
8
9
10
<?xmlversion="1.0"encoding="UTF8"?>
<shapexmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:gradientRadius="750"
android:endColor="@color/bg_gradient_end"
android:startColor="@color/bg_gradient_start"
android:type="radial"/>
</shape>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
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=".MainActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
android:text="@string/welcome"
android:textColor="@color/white"
android:textSize="25sp"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_form_rounded"
android:orientation="vertical">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@null"
android:hint="@string/email"
android:padding="5dp"
android:singleLine="true"
android:id="@+id/email"android:textColor="@color/black"/>
</LinearLayout>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:background="@drawable/bg_button_rounded"
android:text="@string/login"
android:textColor="@color/white"android:onClick="RegisterUser"/>
</LinearLayout>
</RelativeLayout>
activity_greeting.xml
Greeting Screen
1
2
3
4
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
10/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:gravity="center"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="invisible"/>
<ImageView
android:layout_width="275dip"
android:layout_height="275dip"
android:layout_marginBottom="10dp"
android:src="@drawable/greeting_default"android:id="@+id/greetimg"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_form_rounded"
android:orientation="vertical">
<TextView
android:id="@+id/greetingmsg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="40dp"
android:gravity="center"
android:text="@string/welcome"
android:textColor="@color/black"
android:textSize="20sp"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
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.
Make sure you changed the IP address mentioned in the APP_SERVER_URL constant with your Machine/LAN IP
address.
1
2
3
4
5
6
7
8
9
10
11
12
packagecom.prgguru.example;
publicinterfaceApplicationConstants{
//PhpApplicationURLtostoreRegIDcreated
staticfinalStringAPP_SERVER_URL="http://192.168.2.4:9000/gcmwebapp/insertuser.php
//GoogleProjectNumber
staticfinalStringGOOGLE_PROJ_ID="837715578074";
staticfinalStringMSG_KEY="m";
Step 6: Utility.java
Create Utility.Java under the package com.prgguru.example and fill it with below code. It has Utility methods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
packagecom.prgguru.example;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
/**
*ClasswhichhasUtilitymethods
*
*/
publicclassUtility{
privatestaticPatternpattern;
privatestaticMatchermatcher;
//EmailPattern
privatestaticfinalStringEMAIL_PATTERN=
"^[_AZaz09\\+]+(\\.[_AZaz09]+)*@"
+"[AZaz09]+(\\.[AZaz09]+)*(\\.[AZaz]{2,})$";
/**
*ValidateEmailwithregularexpression
*
*@paramemail
*@returntrueforValidEmailandfalseforInvalidEmail
*/
publicstaticbooleanvalidate(Stringemail){
pattern=Pattern.compile(EMAIL_PATTERN);
matcher=pattern.matcher(email);
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
11/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
26
27
28
returnmatcher.matches();
}
}
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).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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;
AsyncTask<Void,Void,String>createRegIdTask;
publicstaticfinalStringREG_ID="regId";
publicstaticfinalStringEMAIL_ID="eMailId";
EditTextemailET;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
applicationContext=getApplicationContext();
emailET=(EditText)findViewById(R.id.email);
prgDialog=newProgressDialog(this);
//SetProgressDialogText
prgDialog.setMessage("Pleasewait...");
//SetCancelableasFalse
prgDialog.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();
}
//WhenRegisterMebuttonisclicked
publicvoidRegisterUser(Viewview){
StringemailID=emailET.getText().toString();
if(!TextUtils.isEmpty(emailID)&&Utility.validate(emailID)){
//CheckifGooglePlayServiceisinstalledinDevice
//PlayservicesisneededtohandleGCMstuffs
if(checkPlayServices()){
//RegisterDeviceinGCMServer
registerInBackground(emailID);
}
}
//WhenEmailisinvalid
else{
Toast.makeText(applicationContext,"Pleaseentervalidemail",
Toast.LENGTH_LONG).show();
}
}
//AsyncTasktoregisterDeviceinGCMServer
privatevoidregisterInBackground(finalStringemailID){
newAsyncTask<Void,Void,String>(){
@Override
protectedStringdoInBackground(Void...params){
Stringmsg="";
try{
if(gcmObj==null){
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
12/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
gcmObj=GoogleCloudMessaging
.getInstance(applicationContext);
}
regId=gcmObj
.register(ApplicationConstants.GOOGLE_PROJ_ID);
msg="RegistrationID:"+regId;
}catch(IOExceptionex){
msg="Error:"+ex.getMessage();
}
returnmsg;
}
@Override
protectedvoidonPostExecute(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.Makesureyo
+msg,Toast.LENGTH_LONG).show();
}
}
}.execute(null,null,null);
}
//StoreRegIdandEmailenteredbyUserinSharedPref
privatevoidstoreRegIdinSharedPref(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);
//MakeRESTfulwebservicecallusingAsyncHttpClientobject
AsyncHttpClientclient=newAsyncHttpClient();
client.post(ApplicationConstants.APP_SERVER_URL,params,
newAsyncHttpResponseHandler(){
//WhentheresponsereturnedbyRESThasHttp
//responsecode'200'
@Override
publicvoidonSuccess(Stringresponse){
//HideProgressDialog
prgDialog.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
@Override
publicvoidonFailure(intstatusCode,Throwableerror,
Stringcontent){
//HideProgressDialog
prgDialog.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,500
else{
Toast.makeText(
applicationContext,
"UnexpectedErrorocccured![MostcommonError:Devicemight"
+"notbeconnectedtoInternetorremoteserverisnotupandrunning],checkforothererro
Toast.LENGTH_LONG).show();
}
}
});
}
//CheckifGooglePlayservicesisinstalledinDeviceornot
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
13/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
privatebooleancheckPlayServices(){
intresultCode=GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
//WhenPlayservicesnotfoundindevice
if(resultCode!=ConnectionResult.SUCCESS){
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){
//ShowErrordialogtoinstallPlayservices
GooglePlayServicesUtil.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
@Override
protectedvoidonResume(){
super.onResume();
checkPlayServices();
}
}
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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;
//ProgressDialogbarobject
ProgressDialogprgDialog;
privatefinalstaticintPLAY_SERVICES_RESOLUTION_REQUEST=9000;
@Override
protectedvoidonCreate(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
//PlayservicesisneededtohandleGCMstuffs
if(!checkPlayServices()){
Toast.makeText(
getApplicationContext(),
"Thisdevicedoesn'tsupportPlayservices,Appwillnotworknormally"
Toast.LENGTH_LONG).show();
}
//Whenjsonisnotnull
if(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'method
aq.id(R.id.greetimg)
.progress(R.id.progress)
.image(prefs.getString("greetimgurl",""),true,true,
0,0,null,AQuery.FADE_IN);
}catch(JSONExceptione){
//TODOAutogeneratedcatchblock
e.printStackTrace();
}
}
//WhenJsonisnull
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
14/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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);
}
}
//CheckifGooglePlayservicesisinstalledinDeviceornot
privatebooleancheckPlayServices(){
intresultCode=GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
//WhenPlayservicesnotfoundindevice
if(resultCode!=ConnectionResult.SUCCESS){
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)){
//ShowErrordialogtoinstallPlayservices
GooglePlayServicesUtil.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
@Override
protectedvoidonResume(){
super.onResume();
checkPlayServices();
}
}
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
packagecom.prgguru.example;
importandroid.app.Activity;
importandroid.content.ComponentName;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.support.v4.content.WakefulBroadcastReceiver;
publicclassGcmBroadcastReceiverextendsWakefulBroadcastReceiver{
@Override
publicvoidonReceive(Contextcontext,Intentintent){
ComponentNamecomp=newComponentName(context.getPackageName(),
GCMNotificationIntentService.class.getName());
startWakefulService(context,(intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
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,soitcanbeupdated
publicstaticfinalintnotifyID=9001;
NotificationCompat.Builderbuilder;
publicGCMNotificationIntentService(){
super("GcmIntentService");
}
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
15/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
publicstaticfinalStringTAG="GCMNotificationIntentService";
@Override
protectedvoidonHandleIntent(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));//WhenMessageisreceivednormallyfromGCMCloudSer
}
}
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);
//Setpendingintent
mNotifyBuilder.setContentIntent(resultPendingIntent);
//SetVibrate,SoundandLight
intdefaults=0;
defaults=defaults|Notification.DEFAULT_LIGHTS;
defaults=defaults|Notification.DEFAULT_VIBRATE;
defaults=defaults|Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
//SetthecontentforNotification
mNotifyBuilder.setContentText("NewmessagefromServer");
//Setautocancel
mNotifyBuilder.setAutoCancel(true);
//Postanotification
mNotificationManager.notify(notifyID,mNotifyBuilder.build());
}
}
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.
[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.
4
Tweet
Share
18
You are always welcome to provide your comments and feedback from 18 Comments box.
Reference
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
16/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
Android GCM
[pgwriteforus]
[pgfeedback]
18Comments
ProgrammerGuruTutorialBlog
Login
Share Favorite
SortbyNewest
Jointhediscussion
Jigar amonthago
Thankyousomuchforthistutorial!!Goodgoing!YOUareAWESOME!:)^_^
Reply Share
AndroidGuru
Mod >Jigar
amonthago
Thanksyou.
Reply Share
FrancescoFerigo 2monthsago
Manymanythanks
Reply Share
AndroidGuru
Mod >FrancescoFerigo
2monthsago
Youarewelcome.
Reply Share
Ray 2monthsago
HI,I'MHAVINGPROBLEMSWITHTHAT
AsyncHttpClientclient=newAsyncHttpClient()
client.post(ApplicationConstants.APP_SERVER_URL,params,
newAsyncHttpResponseHandler(){
//WhentheresponsereturnedbyRESThasHttp
//responsecode'200'
@Override
Reply Share
AndroidGuru
Mod >Ray
2monthsago
YouneedtouseyourserverURL.
1
Reply Share
joe 3monthsago
GreatJobonthetutorial..butiamhavingsometroublewiththeapp..
Irantheappandtheserver..butwheniruntheappittellsme"Thisappwon'trununlessyouupdategoogleplayservices"?iamrunninga
emulator..
thankyou.
Reply Share
AndroidGuru
Mod >joe
2monthsago
GooglePlayServiceisneededforinvokingGCMservice.ItistheprecheckIamdoingincode.
Reply Share
abul 3monthsago
"Youarealwayswelcometoprovideyourcommentsandfeedbackfromcommentbox."
I'dtrytodiscussaboutthisproject,butmyquestionshaveneverbeenapproved.ckckck
Reply Share
AndroidGuru
Mod >abul
2monthsago
HIAbul,
IamnotfulltimebloggersowhenIgettimeIwritetutorialsandalsoapprovecomments.Youcanseeyourquestionstoday.:)
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
17/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
Reply Share
abul 3monthsago
whyigotfailure?wherecaniseetheerror?
1
Reply Share
AndroidGuru
Mod >abul
2monthsago
Pleaseseetheerrorinlogcat.
Reply Share
joe 3monthsago
Ihavesuccessfullycreatedandrantheapp,butwheniopenedtheappandtrytoregister..itcreatedtheregisteridbutthengivesmean
error
UnexpectedErrorOcccured~[MostCommonError:Devicenotbeconnectedtointernetorremoteserverisnotupandrunning,check
othererrorsaswell.
Iamrunningxampponlocalhost.
pleasehelp..thankyou
Reply Share
AndroidGuru
Mod >joe
2monthsago
DidyouchangetheIPaddressinJavafiletoyourLANIPaddress?
Reply Share
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 Share
RahulChauhan 4monthsago
Nicepostbuddy.
Reply Share
MonowarHossain 4monthsago
Wow!VeryNicepostandalsohelpful.Iamreallysurprised
toreadthispost.IknowhereaboutGCM.NicepostBOSS!!!
Reply Share
AndroidGuru
Mod >MonowarHossain
4monthsago
Thankyou.
1
Reply Share
WHAT'STHIS?
ALSOONPROGRAMMERGURUTUTORIALBLOG
HowtoaddFacebooklikebuttoninAndroidapplications?
4comments3monthsago
sugatHi,Itiredyoursampleproject,itdoesnotwork.Isit
HowtopoststatusupdateorsharelinkinFacebookfrom
AndroidApplication?
2comments2monthsago
beacuseofFBapproval?oramImissingsomething?
AndroidGuruAppwillstopworking.Itisbettertocheckif
facebookappisinstalledalreadyinAndroiddevice.
HowtosyncRemoteMySQLDBtoSQLiteonAndroid?
Howtopickimagefromgallery?
76comments7monthsago
1comment4monthsago
AsadAlibrohowdidusolvedit,,,ihavethesame
MeHowcanIstorethisimage,soIcanseeitagainwhen
problem..helpmetheniwillworkonhavingbothmysqlandsqlite
synchronized...
openingtheappagain?
Subscribe
AddDisqustoyoursite
Recent Posts
Privacy
Recent Comments
app developer
Android Guru on Introduction
How to Position Toast in
to GCM
Android Application?
Android Guru on How to send
How to Receive Simple Data
service?
Tags
Action Bar Activity AJAX android
apps development
Basics
Android
android development
Application
Button
Call
Camera
18/19
/
/
AndroidMultiCastPushNotificationsusingGCM[GreetingApp]|AndroidTutorial
http://programmerguru.com/androidtutorial/androidmulticastpushnotificationsusinggcm/
19/19