Android Push Notification using Google Cloud Messaging (GCM) – Part 2
If you are here, you are already done with Google API Console Registration and WebServer Configuration. If not, it is suggested to refer Google API Console Registration and WebServer Configuration before proceeding further.
GCM Enabled Android Application
1. Setting Google Play Service For enabling support, Google Play Services
library is required to add in project. Refer to Google Play Services Setup.
If you are eclipse user, Go to menu Window -> Android SDK Manager -> Extras
. Install Google Play Service library from there. It will be downloaded to “sdk\extras\google\google_play_services”.
2. Preparing application manifest Add following permissions in your application manifest file. Declare a receiver in your manifest to receive GCM message and registration id. Add meta data for google play services. Add a service for handling GCM messages in background. Replace all occurrences of com.androidsrc.gcmsample
with your package name.
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 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidsrc.gcmsample" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="21" /> <!-- For accessing Internet --> <uses-permission android:name="android.permission.INTERNET"/> <!-- For checking current network state --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <!-- For waking device from sleep for showing notification --> <uses-permission android:name="android.permission.WAKE_LOCK"/> <!-- For vibrating device --> <uses-permission android:name="android.permission.VIBRATE"/> <!-- For receiving GCM messages --> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <!-- For protecting GCM messages so that only your app can receive them --> <permission android:name="com.androidsrc.gcmsample.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="com.androidsrc.gcmsample.permission.C2D_MESSAGE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- For receiving GCM message and registration success --> <receiver android:name=".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.androidsrc.gcmsample" /> </intent-filter> </receiver> <service android:name=".GCMIntentService" /> <!-- make sure to add google-play-services_lib from project properties->android->library--> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> </application> </manifest> |
3. Setting up UI We will keep it simple. Our launcher activity will have simple one button to register it with GCM server. And one text view for showing registration id after successful registration. Modify your layout res/layout/activity_main.xml
as below.
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 |
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <LinearLayout xmlns: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:gravity="center" android:orientation="vertical" tools:context="com.androidsrc.gcmsample.MainActivity" > <Button android:id="@+id/register_gcmserver" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical|center_horizontal" android:text="Register with GCM Server" /> <TextView android:id="@+id/regId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:gravity="center_vertical|center_horizontal" android:textSize="30dp" /> </LinearLayout> |
4. Setting up SRC files
Create GCMBroadcastReceiver
which will extend WakefulBroadcastReceiver
in order to keep device awake while processing message from GCM.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.androidsrc.gcmsample; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; public class GCMBroadcastReceiver extends WakefulBroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // Attach component of GCMIntentService that will handle the intent in background thread ComponentName comp = new ComponentName(context.getPackageName(), GCMIntentService.class.getName()); // Start the service, keeping the device awake while it is launching. startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); } } |
Create service GCMIntentService
which will extend IntentService
to perform task of showing notification in a background thread.
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 |
package com.androidsrc.gcmsample; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; public class GCMIntentService extends IntentService { public static final int NOTIFICATION_ID = 1000; NotificationManager mNotificationManager; NotificationCompat.Builder builder; public GCMIntentService() { super(GCMIntentService.class.getName()); } @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); if (!extras.isEmpty()) { // read extras as sent from server String message = extras.getString("message"); String serverTime = extras.getString("timestamp"); sendNotification("Message: " + message + "\n" + "Server Time: " + serverTime); } // Release the wake lock provided by the WakefulBroadcastReceiver. GCMBroadcastReceiver.completeWakefulIntent(intent); } private void sendNotification(String msg) { mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( this).setSmallIcon(R.drawable.ic_launcher) .setContentTitle("Notification from GCM") .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) .setContentText(msg); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } } |
In MainActivity.java
, on clicking of register button we will handle task of registering our application with help of GoogleCloudMessaging
api’s. After getting registration id from GCM, we will register with our web server for saving registration id.
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 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 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 |
package com.androidsrc.gcmsample; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class MainActivity extends Activity { // Resgistration Id from GCM private static final String PREF_GCM_REG_ID = "PREF_GCM_REG_ID"; private SharedPreferences prefs; // Your project number and web server url. Please change below. private static final String GCM_SENDER_ID = "YOUR_PROJECT ID"; private static final String WEB_SERVER_URL = "YOUR_WER_SERVER_URL"; GoogleCloudMessaging gcm; Button registerBtn; TextView regIdView; private static final int ACTION_PLAY_SERVICES_DIALOG = 100; protected static final int MSG_REGISTER_WITH_GCM = 101; protected static final int MSG_REGISTER_WEB_SERVER = 102; protected static final int MSG_REGISTER_WEB_SERVER_SUCCESS = 103; protected static final int MSG_REGISTER_WEB_SERVER_FAILURE = 104; private String gcmRegId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); registerBtn = (Button) findViewById(R.id.register_gcmserver); registerBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Check device for Play Services APK. if (isGoogelPlayInstalled()) { gcm = GoogleCloudMessaging.getInstance(getApplicationContext()); // Read saved registration id from shared preferences. gcmRegId = getSharedPreferences().getString(PREF_GCM_REG_ID, ""); if (TextUtils.isEmpty(gcmRegId)) { handler.sendEmptyMessage(MSG_REGISTER_WITH_GCM); } else { regIdView.setText(gcmRegId); Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_SHORT).show(); } } } }); regIdView = (TextView) findViewById(R.id.regId); } private boolean isGoogelPlayInstalled() { int resultCode = GooglePlayServicesUtil .isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, ACTION_PLAY_SERVICES_DIALOG).show(); } else { Toast.makeText(getApplicationContext(), "Google Play Service is not installed", Toast.LENGTH_SHORT).show(); finish(); } return false; } return true; } private SharedPreferences getSharedPreferences() { if (prefs == null) { prefs = getApplicationContext().getSharedPreferences( "AndroidSRCDemo", Context.MODE_PRIVATE); } return prefs; } public void saveInSharedPref(String result) { // TODO Auto-generated method stub Editor editor = getSharedPreferences().edit(); editor.putString(PREF_GCM_REG_ID, result); editor.commit(); } Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_REGISTER_WITH_GCM: new GCMRegistrationTask().execute(); break; case MSG_REGISTER_WEB_SERVER: new WebServerRegistrationTask().execute(); break; case MSG_REGISTER_WEB_SERVER_SUCCESS: Toast.makeText(getApplicationContext(), "registered with web server", Toast.LENGTH_LONG).show(); break; case MSG_REGISTER_WEB_SERVER_FAILURE: Toast.makeText(getApplicationContext(), "registration with web server failed", Toast.LENGTH_LONG).show(); break; } } ; }; private class GCMRegistrationTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub if (gcm == null && isGoogelPlayInstalled()) { gcm = GoogleCloudMessaging.getInstance(getApplicationContext()); } try { gcmRegId = gcm.register(GCM_SENDER_ID); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return gcmRegId; } @Override protected void onPostExecute(String result) { if (result != null) { Toast.makeText(getApplicationContext(), "registered with GCM", Toast.LENGTH_LONG).show(); regIdView.setText(result); saveInSharedPref(result); handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER); } } } private class WebServerRegistrationTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { URL url = null; try { url = new URL(WEB_SERVER_URL); } catch (MalformedURLException e) { e.printStackTrace(); handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE); } Map<String, String> dataMap = new HashMap<String, String>(); dataMap.put("regId", gcmRegId); StringBuilder postBody = new StringBuilder(); Iterator iterator = dataMap.entrySet().iterator(); while (iterator.hasNext()) { Entry param = (Entry) iterator.next(); postBody.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { postBody.append('&'); } } String body = postBody.toString(); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); int status = conn.getResponseCode(); if (status == 200) { // Request success handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_SUCCESS); } else { throw new IOException("Request failed with error code " + status); } } catch (ProtocolException pe) { pe.printStackTrace(); handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE); } catch (IOException io) { io.printStackTrace(); handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE); } finally { if (conn != null) { conn.disconnect(); } } return null; } } } |
We are done with Sample GCM Application. After registration, Go to your web server and try sending message to registered devices via GCM. You will receive push notification from GCM server.