How to add a push notification in my own android app

60,318

Solution 1

I am posting demo application of Google Cloud Messaging.

Make sure you create demo application with API level equal or higher than Android OS 2.2 with Google API

User have to signed in at-least one Google Account to use this service.

First you have to add GCM library.

Than create on class which I named GCMIntentService which extends GCMBaseIntentService as follows:

package com.example.gcmdemo;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMConstants;

public class GCMIntentService extends GCMBaseIntentService {

     private static final String TAG = "Push Notification Demo GCMIntentService";

    @Override
    protected void onError(Context context, String errorId) {

        if(GCMConstants.ERROR_ACCOUNT_MISSING.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Account Missing");
        } else if(GCMConstants.ERROR_AUTHENTICATION_FAILED.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Authentication Failed");
        } else if(GCMConstants.ERROR_INVALID_PARAMETERS.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Invalid Parameters");
        } else if(GCMConstants.ERROR_INVALID_SENDER.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Invalid Sender");
        } else if(GCMConstants.ERROR_PHONE_REGISTRATION_ERROR.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Phone Registration Error");
        } else if(GCMConstants.ERROR_SERVICE_NOT_AVAILABLE.equalsIgnoreCase(errorId)) {
            Log.v(TAG, "Error Service Not Available");
        } 
    }

    @Override
    protected void onMessage(Context context, Intent intent) {

        // App Server Sends message as key value pairs 
        String value1 = intent.getStringExtra("key1");
        String value2 = intent.getStringExtra("key2");

        Log.v(TAG, "key1: "+value1 );
        Log.v(TAG, "key2: "+value2 );
    }

    @Override
    protected void onRegistered(Context context, String regId) {

        Log.v(TAG, "Successfull Registration : "+regId);
    }

    @Override
    protected void onUnregistered(Context context, String regId) {

        Log.v(TAG, "Successfully Unregistred : "+regId);
    }

    @Override
    protected String[] getSenderIds(Context context) {
        return super.getSenderIds(context);
    }

    @Override
    protected void onDeletedMessages(Context context, int total) {
        super.onDeletedMessages(context, total);
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        return super.onRecoverableError(context, errorId);
    }
}

Here is how you should check registration in following demo activity :

package com.example.gcmdemo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity {

    private static final String TAG = "Push Notification Demo Activity";
    private static final String SENDER_ID = "1069713227710";

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

        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
          GCMRegistrar.register(this, SENDER_ID);
        } else {
          Log.v(TAG, "Already registered : "+regId);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

And finally the demo manifest :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gcmdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <permission
        android:name="com.example.gcmdemo.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.example.gcmdemo.permission.C2D_MESSAGE" />

    <!-- App receives GCM messages. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- GCM connects to Google Services. -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.google.android.gcm.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.example.gcmdemo" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" />
    </application>

</manifest>

Also you will need third party server side script as specified here.

Solution 2

Sending Push Notification using FCM

Google deprecated the Google Cloud Messaging (GCM) and launched new Push notification server that is Firebase Cloud Messaging (FCM). FCM is same like GCM, FCM is also a cross-platform messaging solution for mobile platforms

Firebase Cloud Messaging can send three types of messages (Message types)

1.Notification Message

2.Data Message

3.message with both Notification and Data

Firebase Cloud Messaging Integrating steps:-

1.SetUp New Project or Import project in Firbase Console(https://firebase.google.com/)

2.Add the Same Package Name of App in Firebase App.

3.Get the "google-services.json" file and put that file to your project’s app folder.This file contains all the Urls and the Keys for Google service's, So don't change or edit this file.

4.Add new Gradle dependencies in Project for Firebase.

//app/build.gradle
dependencies {
  compile 'com.google.firebase:firebase-messaging:9.6.0'
}

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

5.Create a Class that contains all the constant values that we use across the app for FCM.

public class Config {
 public static final String TOPIC_GLOBAL = "global";
 // broadcast receiver intent filters
public static final String REGISTRATION_COMPLETE = "registrationComplete";
public static final String PUSH_NOTIFICATION = "pushNotification";

// id to handle the notification in the notification tray
public static final int NOTIFICATION_ID = 100;
public static final int NOTIFICATION_ID_BIG_IMAGE = 101;
public static final String SHARED_PREF = "ah_firebase";
 }

6. Create a class named MyFirebaseInstanceIDService.java which will receives the firebase registration id which will be unique to each app. Registration id is used to send message to a single device.

    public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences
        storeRegIdInPref(refreshedToken);

        // sending reg id to your server
        sendRegistrationToServer(refreshedToken);

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

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);
    }

    private void storeRegIdInPref(String token) {
    SharedPreferences pref =     getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);
        editor.commit();
    }
    }

7.Create one more service class named MyFirebaseMessagingService.java. This will receive firebase messages.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }
    }
 private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }else{
            // If the app is in background, firebase itself handles the notification
        }
    }
 /**
     * Showing notification with text only
     */
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
    }

    /**
     * Showing notification with text and image
     */
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
    }
}

8.In the AndroidManifest.xml add these two firebase services MyFirebaseMessagingService and MyFirebaseInstanceIDService.

 <!-- Firebase Notifications -->
        <service android:name=".service.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".service.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <!-- ./Firebase Notifications -->

Now simply Send your First Message

Notes :

*1.Read the Google Doc for Firebase Cloud Messaging *

2.If you want to Migrate a GCM Client App for Android to Firebase Cloud Messaging follow these steps and Doc (Migrate a GCM Client App)

3.Android Sample tutorial and Code (Receive Reengagement Notifications)

Solution 3

personally suggest you that instead of GCM there is also other library named Parse for PushNotification, it works same as Google Cloud Messaging but it is so so so so much easy then GCM

You have to just download JAR file and simple two-three line of code for PUSH-NOTIFICATION

to learn use this site https://parse.com/tutorials/android-push-notifications

Even you don't have to use PHP or any kind of server side code it provide you facility

look i will give u demo

  Parse.initialize(this, "YOUR_APP_ID", "YOUR_CLIENT_KEY");
  PushService.setDefaultPushCallback(this, YourDefaultActivity.class);

from above code is enough for receiving push notification

if you want to send notification they provide nice UI look the picture of UI they provide

enter image description here

Share:
60,318

Related videos on Youtube

user1676640
Author by

user1676640

Updated on November 29, 2020

Comments

  • user1676640
    user1676640 over 3 years

    I have developed a push notification application in Android from this tutorial:push notification in android app. The register button is displayed when I run the app. When I click on the register button, and when registration is successful, a notification is displayed on my device.

    How can I include it in my own app? My app has one xml parsing example app. Here when any new item is added, I wish to display (the new order is displayed ) a notification message on the device. It is automatically generated here.

  • user1676640
    user1676640 over 11 years
    ya i have done above methods.the app is successfully run and displayed listview.i have to insert one item on my database successfully afterthat i ll go and see my device no notification message is display on my device.
  • Sunil Kumar
    Sunil Kumar over 9 years
    limit the amount of push notices in GCM?
  • Phil L.
    Phil L. about 9 years
    Parse is commercial offer. Does GCM have similar restrictions (price) after a certain limit?
  • kacper3w
    kacper3w about 8 years
    parse is only commercial in SaaS model. they also have the open source version of their server on github
  • Saurabh
    Saurabh about 6 years
    What is NotificationUtils, no reference of it?
  • Alex Cuadrón
    Alex Cuadrón over 5 years
    GCM is deprecated. Don't use it