Push Notifications using GCM in Android Studio
According to Google’s documentations “Google Cloud Messaging (GCM) is a free service that enables developers to send messages between servers and client apps. This includes downstream messages from servers to client apps, and upstream messages from client apps to servers”. The GCM service handles all aspects of queueing of messages and delivery to the target Android application running on the target device.
Instead of getting notified about others messages here is a good spybubble review click here and get the app that makes a video of everything they do on their screen. Did they just download that new social media app to chat with their ex?
Creating API key
1.Go to Google Developer Console and select Get a configuration file.
2.Create new app or select from your existing app. write your package name also and click on continue to choose and configure services.
3.Select cloud messaging and click on Enable Google Cloud Messaging.
4.Note down generated API key and sender id, click on Continue to generate configuration file.
5.Click on Download google-services.json and save it for later use.
Creating Android Project for GCM
1.Create a new android project in your Android Studio and add dependency for GCM.
- Add a dependency to your project level build.gradle
1classpath 'com.google.gms:google-services:1.5.0-beta2' - Add a plugin to your app level builg.gradle
1apply plugin: 'com.google.gms.google-services' - Add a dependency to your app level build.gradle
123dependencies {compile "com.google.android.gms:play-services:8.4.0"}
2.Put downloaded configuration file google-services.json inside app folder.
3.Add permissions in manifest.xml
1 |
4.Define GCM services in manifest.xml
1 |
5.Before generating GCM device id, check whether Gooogle Play Service is updated or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, 9000).show(); } else { finish(); } return false; } return true; } |
6.Now generate GCM device id by writing following code in seperate thread apart from main thread.
1 2 3 4 5 6 7 8 9 10 11 12 |
class GenerateToken extends Thread { public void run() { try { InstanceID instanceID = InstanceID.getInstance(MainActivity.this); final String token = instanceID.getToken("", GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Log.e("device_token", token); } catch (final Exception e) { e.printStackTrace(); } } } |
7.Now calling this method from your onCreate() will give you device token
1 2 |
if(checkPlayServices()) new GenerateToken().start(); |
8.Create GCMService which will be called when receive any notification.
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 |
public class MyGcmListenerService extends GcmListenerService { @Override public void onMessageReceived(String from, Bundle data) { super.onMessageReceived(from, data); Log.e("received","message"); generateNotification(this, data.getString("message")); } private static void generateNotification(Context context, String message) { int icon = R.mipmap.ic_launcher; long when = System.currentTimeMillis(); Intent notificationIntent = new Intent(context, MainActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Resources res = context.getResources(); Notification notification = new NotificationCompat.Builder(context) .setCategory(Notification.CATEGORY_PROMO) .setContentTitle(context.getResources().getString(R.string.app_name)) .setContentText(message) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(res, icon)) .setAutoCancel(true) .setContentIntent(contentIntent) .setPriority(Notification.PRIORITY_HIGH) .setDefaults(Notification.DEFAULT_SOUND).build(); nm.notify(456, notification); } } |
Download full source code from GITHUB.
Ravi Rupareliya
Latest posts by Ravi Rupareliya (see all)
- Dialogflow Entities With Actions on Google - May 7, 2020
- Actions on Google Using Cloud Functions - February 3, 2020
- Create WhatsApp Stickers Android Application - April 19, 2019