Android GCM Push notification.

GCM Push notification:

Generally push notifications are used to notify or intimate when the user gets any message from their server to their application through GCM. These messages are shown to the users in the status bar. So In this tutorial, we are going to see how to handle push notification in Android and test it through the Online tool to generate dummy data. To become a master in push notification implementation in Android, follow the steps.

STEP 1:

Go to the URL

https://console.developers.google.com/project/fiery-plate-106917

you will be finding this screen after logging in to your Gmail Account.

STEP 2:

Click select a project from the top.

A drop-down appears as follows.

Now select Create a project

STEP 3:

In the Create a Project screen, type your application name or project name (I have used my project name as GCMDemo). Then finally check the terms and condition box and click create button. That’s it your project has been created successfully.

STEP 4:

Now kindly make a note of your project id. Please follow the screenshots below.

The red highlighted part is your Sender ID or project (12 digits).

STEP 5:

Select credentials from the side menu

click Add credentials button and then choose the API Key option.

Please follow the flow with a green highlighted portion in the above image.

STEP 6:

Now create a New Key dialog box appears and select the server key option.

After choosing the Server key option, now simply click Create button.

Thumbs up! you’re done. Make a note of your API Key

STEP 7:

Tired of following the above steps? Don’t worry! You may become a pro in GCM once you implement the setup successfully and start playing with GCM. Now let us see the coding part as follows.

GCMUtils.java

This is where you will assign your project ID. Change your project ID to the one we generated in STEP 4.

package com.takeoffandroid.GCMDemo.GCMPushNotification;
public class GCMUtils {
    public static final String SENT_TOKEN_TO_SERVER = “sentTokenToServer”;
    public static final String REGISTRATION_COMPLETE = “registrationComplete”;
    public static final String PROJECT_ID = “YOUR_PROJECT_ID”; //EXAMPLE: 123456789101
}

This is where you will register and get your GCM Register Id. Note:

Log.i (TAG, “Token “ + token); //your Register ID will be printed in the log.

Kindly make a note of it. This is the ID that we will be sent to the server to get push notifications.

GCMRegistrationIntentService.java

package com.takeoffandroid.GCMDemo.GCMPushNotification;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

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

public class GCMRegistrationIntentService extends IntentService {

private static final String TAG = "IntentService";

public GCMRegistrationIntentService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences =          PreferenceManager.getDefaultSharedPreferences(this);
try {
    InstanceID instanceID = InstanceID.getInstance(this);
    String token = instanceID.getToken(GCMUtils.PROJECT_ID,
    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
    Log.i(TAG, "Token " + token);
    sendRegistrationToServer(token);
    sharedPreferences.edit().putBoolean(GCMUtils.SENT_TOKEN_TO_SERVER,      true).apply();
} catch (Exception e) {
    Log.d(TAG, "Failedtorefresh", e);
    sharedPreferences.edit().putBoolean(GCMUtils.SENT_TOKEN_TO_SERVER,         false).apply();
}

// Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent registrationComplete = new        Intent(GCMUtils.REGISTRATION_COMPLETE);
  LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}

/**
* Persist registration to third-party servers.
*
* Modify this method to associate the user's GCM registration token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
}

GCMListenerService.java

This is the class where we will be building the notification title, icon and bundle data (message) that we received in onMessageReceived method.

Note: Keep the default Key as a “message” for the bundle data. Let us follow “message” as a global standard.

/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.takeoffandroid.GCMDemo.GCMPushNotification;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GcmListenerService;
import com.takeoffandroid.GCMDemo.R;
import com.takeoffandroid.GCMDemo.activity.MainActivity;

public class GCMListenerService extends GcmListenerService {

private static final String TAG = "GCMListenerService";

@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);  
    sendNotification(message);
}

/**
* Create and show a simple notification containing the received GCM message.
*
* @param message GCM message received.
*/
private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri=          RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new            NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.gcm_logo)
.setContentTitle ("Takeoff Android").setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent (pendingIntent);
    NotificationManager notificationManager =
    (NotificationManager)     getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0 /* ID of notification */,     notificationBuilder.build());
}
}

GCMInstanceIDListenerService.java

This class is called if InstanceID (i.e. Register ID) token is updated.

package com.takeoffandroid.GCMDemo.GCMPushNotification;
import android.content.Intent;

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

public class GCMInstanceIDListenerService extends InstanceIDListenerService {

private static final String TAG = "MyInstanceIDLS";

/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. This call is initiated by the
* InstanceID provider.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {

// Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
    Intent intent = new Intent(this,   GCMRegistrationIntentService.class);
    startService(intent);
}
// [END refresh_token]
}

Online Tool:

Go to URL: GCM Server Testing For Android

Please enter the API key that we have generated in STEP 6 and enter Register ID that was printed in the log from GCMRegistrationIntentService.java class. Finally in the message box type message=success.

That’s it, you’re done with GCM. Happy coding! Cheers!!

Download complete code

Originally published at takeoffandroid.com on September 26, 2015.

0
Subscribe to my newsletter

Read articles from Chandrasekar Kuppusamy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chandrasekar Kuppusamy
Chandrasekar Kuppusamy