Android Firebase Cloud Messaging (Push Notification) with Server Admin in Php and MYSQL database

In this tutorial, we are going to learn how to add Android Firebase Cloud Messaging – Push Notification with Server Admin built with Php and Mysql database.

Even since Google acquired Firebase, Google has suggested that you create or moving your existing Google Cloud Messaging applications to Firebase platform.

If you still want to implement Push Notification using Google Cloud Messaging, I wrote a popular tutorial which you are read Google Cloud Messaging using OKHttp.

Since we are going to create our own back-end which will allow us to send Push Notitification to Firebase Cloud Messaging and into turn the message will be sent to the device(s) it is meant for.

 

Server Web Application for Push Notification

First, we will start with our server side application. Open your IDE of choice and create a new folder. Name the folder firebase. The image below is a brief idea on how our server side will look like.

android push notification

We are going to use a local web server (WAMP). Before we start with our web application, we will first create the database. Click on the WAMP server icon, select the menu phpMyAdmin to setup the database structure.

Click and open PhpMyAdmin, create a database and name it firebase. Create a table inside the database and name it firebase. The table will contain two columns – id and token. The token column will hold store device tokens.

<color name="colorPrimary">#3F51B5</color>
CREATE TABLE IF NOT EXISTS `firebase` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `token` varchar(300) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

Database Connection

In other to connect our web app to database, we will create a configuration file that we will put all database connection details.

 

config.php

Create a new php file in the root firebase folder and name it config.php. Open the config.php file and add the code below to the file.

 define("DB_HOST", "");
 define("DB_USER", "");
 define("DB_PASSWORD", "");
 define("DB_NAME", "");

define("SERVER_KEY", "");

Enter your host, database, username and password detail. For the server key, we will fill it in when we create our Firebase application.

 

db.php

Create a new file called db.php which will include our configuration file and connect to our web app to database.

include_once 'config.php';

class DbConnect{	
	
	private $connect;	
	
	public function __construct(){
		
		$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
		 
		if (mysqli_connect_errno($this->connect))
		{
			echo "Failed to connect to MySQL: " . mysqli_connect_error();  
		}
	}
	
	public function getDb(){
		
		return $this->connect;
	}	
}

database.php

Next we will create a database.php file with two methods we will use in your application. One method is used to store client device token to the database while the second one is used to return the token stored in the database.

Open the file and add the code below to the file.

include_once 'db.php';

 class Database{
	
	public function __constructor(){
	}
	
	public function insertUserDeviceToken($token){			
		$com = new DbConnect();	
		$sql = "insert into firebase(token) values ('$token')";			
		$success = mysqli_query($com->getDb(), $sql);
		if($success){
			echo json_encode(array('token' => 1), JSON_PRETTY_PRINT);
		}else{
			echo json_encode(array('token' => 0), JSON_PRETTY_PRINT);
		}	
	}
	
	public function getRegisteredToken(){
		
		$com = new DbConnect();
		$sql = "select * from firebase order by id desc limit 1";
		$result = mysqli_query($com->getDb(), $sql);
		$row = mysqli_fetch_row($result);
		$token = $row[1];
		return $token;
	}	
}

token.php

Since we have to in some way communicate with android client in other to store its unique token identification to the database, we will create a file called token.php. This file will accept all incoming network calls from the client application, it will retrieve the passed token and store it to the database table.

Open the file and add the code to the file.

if(isset($_POST['token'])){	
	$token = $_POST['token'];

    include_once 'database.php';	
    $deviceTokenRegistration = new Database();
    $deviceTokenRegistration->insertUserDeviceToken($token);


sendnotification.php

We have dealt with android client network call, now we will create a class that will contain a method that will aid in sending a post request to Firebase Cloud Messaging from the web server app.

Create a new php file and name it sendnotification.php. Open the file and add the code below to the file.

class SendNotification{ 	
 	
	public function __construct(){		
	}
	
	public function sendPushNotificationToGCMSever($token, $message){
		
		include_once 'config.php';
		
        $path_to_firebase_cm = 'https://fcm.googleapis.com/fcm/send';
		
		$fields = array(
            'to' => $token,
            'notification' => array('title' => 'Working Good', 'body' => 'That is all we want'),
            'data' => array('message' => $message)
        );
 
        $headers = array(
            'Authorization:key=' . SERVER_KEY,
            'Content-Type:application/json'
        );		
		$ch = curl_init();
 
        curl_setopt($ch, CURLOPT_URL, $path_to_firebase_cm); 
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); 
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    
        $result = curl_exec($ch);
       
        curl_close($ch);

        return $result;
	}
 }


servertofirebase.php

We will create a page we the message form will be posted to. This page will get the POST global variable from the admin.php form. It will retrieve the message to push and the client device token.

Create a php file and name it serverfirebase.php. Open the file and add the below code to the page.

include_once 'sendnotification.php';

if(isset($_POST['token']) && isset($_POST['message'])){
	
	$token = $_POST['token'];
	$message = array("FCM" => $_POST['message']);
	
	$serverObject = new SendNotification();	
	$jsonString = $serverObject->sendPushNotificationToGCMSever($token, $message);

	$jsonObject = json_decode($jsonString);

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”utf-8″>

<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>

<meta name=”viewport” content=”width=device-width, initial-scale=1″>

<title>Admin Section Login</title>

<link href=”style.css” rel=”stylesheet”>

</head>

<body>

<div id=”form-wrapper”>

<?php

if(isset($jsonObject->success) && $jsonObject->success == 1){ ?>

<h2 class=”send-success”> Firebase Push Notification successfully sent</h2>

<?php } else{ ?>

<h2 class=”send-success”> Invalid Registration. Make sure your have provided the correct details</h2>

<?php } ?>

<h3 class=”back-link”><a href=”admin.php”> Go back the Admin dashboard</a></h3>

</div>

</body>

</html>

 

admin.php

We will create a new php file which will contain a form with Textarea and a hidden text input. When message to be pushed is added, it send the data to servertofirsbase.php file.

Add the code below to this file.

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”utf-8″>

<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>

<meta name=”viewport” content=”width=device-width, initial-scale=1″>

<title>Admin Section Login</title>

<link href=”style.css” rel=”stylesheet”>

</head>

<body>

<div id=”form-wrapper”>

<?php

include_once ‘database.php’;

$db = new Database();

$token = $db->getRegisteredToken();

echo $token;

?>

</style>

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js”></script>

<script>

$(function(){

$(“textarea”).val(“”);

});

function isEmptyTextBox(){

var msgLength = $.trim($(“textarea”).val()).length;

if(msgLength == 0){

alert(“Text box must not be empty”);

return false;

}else{

return true;

}

}

</script>

<p id=”logo”><img src=”images/fly.png” alt=”logo” /></p>

<h2>Firesbase Cloud Messaging (Php Web Server) </h2>

<p>Firebase Downstream Push Notification</p>

<form method=”post” action=”Servertofirebase.php” onsubmit=”return isEmptyTextBox()”>

<input type=”hidden” id=”user_id” name=”token” value=”<?php echo $token ? $token : 0 ?>”>

<textarea cols=”70″ rows=”12″ name=”message” cols=”45″ placeholder=”Message via Firebase Cloud Messaging”></textarea> <br/>

<input id=”button-send” type=”submit” value=”Send Firebase Push Notification” />

</form>

</div>

</body>

</html>

 

style.css

Since we have created some html interface, we are going to use to styling it to make our UI look appealing and beautiful.

Create a style.css file in the firebase folder and add the style below.

body{
	background-color: #50a9f6;
}

#form-wrapper{
	width: 500px;
	height: 500px;
	background-color: #039be5;
	margin: 20px auto;	
	padding: 60px; 
}

#logo{
	width: 150px;
	height: 150px;
	margin: 20px auto;
}

#button-send{
	width: 300px;
	margin: 20px auto;
	display: block;
	background-color: #c02a2a;
	border: 0px;
	padding: 10px;
	color: #ffffff;
}
.send-success{
	color: #ffffff;
}
.back-link{
	width: 270px;
	height: 50px;
	margin: 80px auto;
	color: blue;
	display: block;
}

 

Firebase Application Setup

Since we have finished with the server side application, now we have to configure Firebase and include it in our android app dependency libraries.

If you do not have a Firebase account, Go the Firsbase webite  and create a new account.

Move over to your Firebase console to create a new Firebase project. Click on the create a new project button.

In the window modal, enter the name of you project and your country as shown in the image below

Android firebase

Click on the create project button to continue. In the console, click the button add Firebase to your android app as shown below

Android firebase

In the next window, add the Package name of your application and click the Add App button as shown below.

Android firebase

Click the continue button to download a Json configuration file which will be added in the root App directory of your project. See the image below

Android firebase

Following the instructions on how to add the Google Services plugin and the Firebase SDK in build.gradle as shown below.

Android firebase

We have successfully added Firebase to our project. We will now focus on our android project.

 

Create New Android Project

We will create a new android android app in Android Studio. Thereafter, we will integrate our Firebase project.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidFirebaseCloudMessaging

Package: com.inducesmile.androidfirebasecloudmessaging

Select Blank Activity

Name your activity : MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

 

Build.gradle

We are going to modify our project and app level build.gradle file.

First, add rules to your root-level build.gradle file, to include the google-services plugin:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

Then, in your module Gradle file (usually the app/build.gradle), add the apply plugin line at the bottom of the file to enable the Gradle plugin:

apply plugin: ‘com.android.application’

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.google.firebase:firebase-messaging:9.0.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.6.1'
}
apply plugin: 'com.google.gms.google-services'

We will also add some other dependency libraries that we will make use of in the application. Since you have to make network calls, we will use Volley for that and also Gson to convert the returned Json to plain Java objects.

 

Strings.xml

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

<resources>
    <string name="app_name">Firebase Cloud Messaging</string>
    <string name="notice_board">Subscribe To Our Health Tips </string>
    <string name="our_goal">Stay health and enjoy life in fullness</string>
    <string name="instruction">If you are hoping to stay health you are welcome to join us in our journey with million of people world wide on useful and life changing tips that will not
    only make you to stay health but strong as you grow older. </string>
    <string name="subscribe">Subscription status </string>
    <string name="status">Welcome back. Your subscription is still valid</string>
    <string name="registered">You can receive notification </string>
    <string name="un_register">You cannot receive notification</string>
</resources>

Colors.xml

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBlack">#000000</color>
</resources>

 

Mainfest.xml

As was stated before about network call, we are going to add internet user permission for access to internet. Open the Mainfest.xml file and add the Internet permission.

Beside the user permission, we are going to register two services which the android client app will use to communicate with the Firebase Cloud Messaging.

The two services are the Firebase Message Service which is used to pass notification message and the Firebase InstanceId which generates and updates the device unique Id token.

The complete code for this file is as shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.firebasecloudmessaging">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".CustomFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service
            android:name=".CustomFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>

 

activity_main.xml

Open the default main layout created for us by Android Studio when the project was initial created. We are going to add some View controls.

Copy and paste below code to the layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.firebasecloudmessaging.MainActivity">
    <TextView
        android:id="@+id/notice_board"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:textSize="24dp"
        android:textStyle="bold"
        android:textColor="@color/colorBlack"
        android:text="@string/notice_board" />
    <TextView
        android:id="@+id/our_goal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorAccent"
        android:text="@string/our_goal"
        android:layout_below="@+id/notice_board"
        android:layout_alignRight="@id/notice_board"
        android:layout_alignEnd="@id/notice_board"/>
    <TextView
        android:id="@+id/instruction"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorBlack"
        android:text="@string/instruction"
        android:lineSpacingExtra="4dp"
        android:layout_below="@+id/our_goal"
        android:layout_marginTop="48dp"
        android:layout_alignLeft="@id/notice_board"
        android:layout_alignStart="@id/notice_board"/>
    <CheckBox
        android:id="@+id/subscribe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/subscribe"
        android:layout_marginTop="32dp"
        android:layout_below="@id/instruction"/>
    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/snackbarPosition"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>


MainActivity.java

For the MainActivity class, instances of the View controls are obtained. The Checkbox and Snackbar is used as an indicator to let a user know if the user can or cannot receive push notification.

Open the MainActivity class and add the code below to the class.

package com.inducesmile.firebasecloudmessaging;
import android.content.BroadcastReceiver;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private CheckBox notificationCheckbox;
    private MySharedPreference mySharedPreference;
    private boolean hasUserSubscribed;
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPlayServices();
        mySharedPreference = new MySharedPreference(this);
        notificationCheckbox = (CheckBox)findViewById(R.id.subscribe);
        final View coordinatorLayoutView = findViewById(R.id.snackbarPosition);
        boolean sentToken = mySharedPreference.hasUserSubscribeToNotification();
        if (sentToken) {
            notificationCheckbox.setChecked(true);
            notificationCheckbox.setEnabled(false);
            notificationCheckbox.setText(getString(R.string.registered));
            Snackbar.make(coordinatorLayoutView, getString(R.string.registered), Snackbar.LENGTH_LONG).show();
        } else {
            notificationCheckbox.setChecked(false);
            notificationCheckbox.setEnabled(false);
            notificationCheckbox.setText(getString(R.string.registered));
            Snackbar.make(coordinatorLayoutView, getString(R.string.un_register), Snackbar.LENGTH_LONG).show();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        checkPlayServices();
    }
    @Override
    protected void onPause() {
        super.onPause();
    }
    private boolean checkPlayServices() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
                finish();
            }
            return false;
        }
        return true;
    }
}

CustomFirebaseInstanceIDService.java

Right click on your project packaage and select create a new Java file. Name the java file CustomFirebaseInstanceIDService and it will extends from FirebaseInstanceIdService class.

We will override the onTokenRefresh() method of this class to obtain the android device registration token.

Once the token is obtain, it will be send to our server side web application which will in return store the token to the databse.

Open the file you have just created and paste below code in it.

import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.HashMap;
import java.util.Map;
public class CustomFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = CustomFirebaseInstanceIDService.class.getSimpleName();
    private RequestQueue queue;
    private TokenObject tokenObject;
    private MySharedPreference mySharedPreference;
    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Token Value: " + refreshedToken);
        sendTheRegisteredTokenToWebServer(refreshedToken);
    }
    private void sendTheRegisteredTokenToWebServer(final String token){
        queue = Volley.newRequestQueue(getApplicationContext());
        mySharedPreference = new MySharedPreference(getApplicationContext());
        StringRequest stringPostRequest = new StringRequest(Request.Method.POST, Helper.PATH_TO_SERVER_IMAGE_UPLOAD, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
                GsonBuilder builder = new GsonBuilder();
                Gson gson = builder.create();
                tokenObject = gson.fromJson(response, TokenObject.class);
                if (null == tokenObject) {
                    Toast.makeText(getApplicationContext(), "Can't send a token to the server", Toast.LENGTH_LONG).show();
                    mySharedPreference.saveNotificationSubscription(false);
                } else {
                    Toast.makeText(getApplicationContext(), "Token successfully send to server", Toast.LENGTH_LONG).show();
                    mySharedPreference.saveNotificationSubscription(true);
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(Helper.TOKEN_TO_SERVER, token);
                return params;
            }
        };
        queue.add(stringPostRequest);
    }
}

 

CustomFirebaseMessagingService.java

Follow the same pattern we used above to create a new java file and create another java file. Now, we are going to name the file CustomFirebaseMessagingService.java. The CustomFirebaseMessagingService class will extends from FirebaseMessagingService class.

The onMessageReceived(RemoteMessage remoteMessage) method of this class will be overridden so that will get data the different data sent from Firebase Cloud Messaging console.

We will also construct a notification method which will take the message as parameter and notify our device about the new message.

Open this file and add the code below to the file.

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.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class CustomFirebaseMessagingService extends FirebaseMessagingService{
    private static final String TAG = CustomFirebaseMessagingService.class.getSimpleName();
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        String message = remoteMessage.getNotification().getBody();
        sendNotification(message);
    }
    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, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notification_icon)
                .setContentTitle("Firebase Push Notification")
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}

 

Other Java Helpful Classes

MySharedPreference.java

import android.content.Context;
import android.content.SharedPreferences;
public class MySharedPreference {
    private SharedPreferences prefs;
    private Context context;
    public static final String FIREBASE_CLOUD_MESSAGING = "fcm";
    public static final String SET_NOTIFY = "set_notify";
    public MySharedPreference(Context context){
        this.context = context;
        prefs = context.getSharedPreferences(FIREBASE_CLOUD_MESSAGING, Context.MODE_PRIVATE);
    }
    public void saveNotificationSubscription(boolean value){
        SharedPreferences.Editor edits = prefs.edit();
        edits.putBoolean(SET_NOTIFY, value);
        edits.apply();
    }
    public boolean hasUserSubscribeToNotification(){
        return prefs.getBoolean(SET_NOTIFY, false);
    }
    public void clearAllSubscriptions(){
        prefs.edit().clear().apply();
    }
}

 

Helper.java

public class Helper {
    public static final String PATH_TO_SERVER_IMAGE_UPLOAD = "http://nigerianstudentshop.com/firebase/token.php";
    public static final String TOKEN_TO_SERVER = "server_token";
    public static final String REGISTRATION_COMPLETE = "registrationComplete";
}

 

TokenObject.java

import com.google.gson.annotations.SerializedName;
public class TokenObject {
    @SerializedName("token")
    private String token;
    public TokenObject(String token) {
        this.token = token;
    }
    public String getToken() {
        return token;
    }
    public void setToken(String token) {
        this.token = token;
    }
}

Common Error You might face

There are many reason why this error might occur but to avoid any of them make sure that you use the right credentails like correct package name for your project, correct server key and there is no error in your Json object.

Internal Server Error 500

401 unauthorized error

 

Server Json Response Object

If everything goes well and your web server was able to deliver the message to Firebase Cloud Messaging, the following respond will be obtained with succes value 1.

{“multicast_id”:8351874900144453375073,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1466136944890948%8d5bbec18d5bbec1″}]}

push notification

For Failed respond, the success value will be 0.

{“multicast_id”:47144772070319043328,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}

There is much to learn about Firebase Cloud Messaging and I will suggest your read the documentation to get more insight on how things work.

 

Sending message through Firebase Notification Console

You can as well send push notification message from your Firebase notification console. Go to your Firebase console, click on the Notification menu and  select the single device option.

Add your message and a label message which is optional. You can go further to add target and other properties you will like to track.

Add the device unique token id previous obtained will the android app.

When you are done, click the send message button and your message will be push to the device.

firebaseconsole

 

If you are interested to learn how to create a subscribe and unsubscribe push notification in androd or real-time chat application, I will suggest you subscribe to my blog for the next coming posts.

 

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

 

 

Remember to subscribe with your email address so that you will be among the first to receive my new android blog post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it.

46 Comments

    • Inducesmile
    • Inducesmile
    • Inducesmile
    • Inducesmile
    • Inducesmile
          • Inducesmile
    • Inducesmile
    • Inducesmile
    • Inducesmile
    • Inducesmile
    • Inducesmile
    • Inducesmile

Add a Comment