Android (GCM) Push Notification Tutorial

In this tutorial, I will show you how to implement push notifications in your native app for android.

Download the required software packages.

  1. Download and install Android Studio and Android SDK.
  2. Android Studio + SDK – http://developer.android.com/sdk/index.html.

Go to Google Developer (https://developers.google.com/mobile/add). Click Pick a platform.

Google services.

Google services.

Click Enable services for my Android App.

Google Services.

Google Services.

Enter your App name and Android package name. Click Choose and configure services.

Google Services.

Google Services.

Select Cloud Messaging and click Enable Google Cloud Messaging.

Google Services.

Google Services.

Make a note of the server API key and press Close.

Google Services.

Google Services.

Click Generate configuration files.

Google Services.

Google Services.

Click Download google-services.json. Once the file has been generated, download it and place it inside your Android Studio project’s app directory.

Google Services.

Google Services.

Setting up your development environment

Open your Android Studio and choose Start a new Android Studio project.

Start a new Android Studio project

Start a new Android Studio project

Enter your custom Application name, Company Domain and select Project location. Click Next.

Configure your new project.

Configure your new project.

Select Phone and Tablet. Make sure API 15 selected. Click Next.

Configure your new project.

Configure your new project.

Select Empty Activity and click Next.

Configure your new project

Configure your new project

Your app must request the C2D_MESSAGE  permissions, if it isn’t doing so already. Add the following lines inside the tag in your AndroidManifest.xml:

<permission android:name="my.intellij.androidpushnotification.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="my.intellij.androidpushnotification.permission.C2D_MESSAGE" />

The notifications are received in the form of broadcasts. To handle those broadcasts, our app needs a BroadcastReceiver. However, we don’t have to create it manually. We can instead use the GcmReceiver class as the BroadcastReceiver.

The BroadcastReceiver must have an intent-filter that responds to the com.google.android.c2dm.intent.RECEIVE action and the name of its category must match your project’s package name. Add the following code to the manifest

<receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="my.intellij.androidpushnotification" />
    </intent-filter>
</receiver>

Open build.gradle (Project:AndroidPushNotification) and add into dependencies block

classpath 'com.google.gms:google-services:1.5.0'

Next, apply the plugin in the app module’s build.gradle on the top

apply plugin: 'com.google.gms.google-services'

And this code on bottom part in the app module’s build.gradle.

configurations.all {
    resolutionStrategy {
        force 'com.android.support:design:23.4.0'
        force 'com.android.support:support-v4:23.4.0'
        force 'com.android.support:appcompat-v7:23.4.0'
    }
}

To be able to use the GCM API, add com.google.android.gms:play-services as a compile dependency in the same file

compile "com.google.android.gms:play-services:8.3.0"

Create a new java class. Right click on my.intellij.androidpushnotification package > New >Activity > Java Class.

Create a new java class.

Create a new java class.

Name it as RegistrationService and click Ok.

Create New Class

Create New Class

Then replace with this code in RegistrationService.java.

package my.intellij.androidpushnotification;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;

import java.io.IOException;

public class RegistrationService extends IntentService {
    public RegistrationService() {
        super("RegistrationService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        InstanceID myID = InstanceID.getInstance(this);

        try {
            String registrationToken = myID.getToken(
                    getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE,
                    null
            );

            Log.d("Registration Token", registrationToken);

            GcmPubSub subscription = GcmPubSub.getInstance(this);
            subscription.subscribe(registrationToken, "/topics/my_little_topic", null);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Define the service in AndroidManifest.xml.

<service android:name=".RegistrationService" android:exported="false" />

Create a new java class. Right click on my.intellij.androidpushnotification package > New >Activity > Java Class.

Create a new java class.

Create a new java class.

Name it as TokenRefreshListenerService and click Ok.

Create New Class

Create New Class

Then replace with this code in TokenRefreshListenerService.java.

package my.intellij.androidpushnotification;

import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;

public class TokenRefreshListenerService extends InstanceIDListenerService {
    @Override
    public void onTokenRefresh() {
        Intent i = new Intent(this, RegistrationService.class);
        startService(i);
    }
}

Define the service in AndroidManifest.xml.

<service android:name=".TokenRefreshListenerService" android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID" />
        </intent-filter>
    </service>

Open MainActivity.java and replace with this code.

package my.intellij.androidpushnotification;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent i = new Intent(this, RegistrationService.class);
        startService(i);
    }
}

Create a new java class. Right click on my.intellij.androidpushnotification package > New >Activity > Java Class.

Create a new java class.

Create a new java class.

Name it as NotificationsListenerService and click Ok.

Create New Class

Create New Class

Then replace with this code in NotificationsListenerService.java.

package my.intellij.androidpushnotification;

import com.google.android.gms.gcm.GcmListenerService;

public class NotificationsListenerService extends GcmListenerService {

}

Define the service in AndroidManifest.xml.

<service android:name=".NotificationsListenerService" android:exported="false" >
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</service>

Go to https://material.io/icons/ and search for cloud icon. Once you download the icon, place it inside the res folder of your project. Use ic_cloud_black_48dp as the icon.

Google’s Material Design Icons Library

Google’s Material Design Icons Library

Build and run your app. You will an output like this in your android studio console.

Create send.py file and replace with this code.

from urllib2 import *
import urllib
import json
import sys

MY_API_KEY="AIzaSyCJu8pl_GmHLhM9SfFc-31vipg9rsfeD5I"

messageTitle = sys.argv[1]
messageBody = sys.argv[2]

data={
    "to" : "/topics/my_little_topic",
    "notification" : {
        "body" : messageBody,
        "title" : messageTitle,
        "icon" : "ic_cloud_black_48dp"
    }
}

dataAsJSON = json.dumps(data)

request = Request(
    "https://gcm-http.googleapis.com/gcm/send",
    dataAsJSON,
    { "Authorization" : "key="+MY_API_KEY,
      "Content-type" : "application/json"
    }
)

print urlopen(request).read()

Open terminal and run the send.py script.

python send.py “My first push notification” “GCM API is wonderful”

Running the Script

Running the Script