Welcome dear developers to Android firebase push notification tutorial example.

1. Firebase Push Notification Android Example Tutorial

Earlier we were using google cloud messaging(GCM) for push notifications in android.

Firebase is the upgraded version of google cloud messaging (GCM).

Firebase push notification Android tutorial guide you to send push notification from server(PHP-MySQL.)

First, check the output of Firebase push notification Android Studio example then we will develop it.

Step 2: Developing app in Firebase Console

Watch a video for how to make app in firebase console website.

Describing Quick steps of above video

Go to https://firebase.google.com/ and sign in to your google account. Click on Add Project and give project name and country. Click on CREATE PROJECT button. After project is created, click on Add firebase to your Android app button. Give your Android package name and click on Register App button. Click on Download google-services.json button. Move your downloaded JSON file into app folder of your android project as shown in the video.

Step 3: Updating build.gradle(Project: project_name) file:

we need to add following in dependencies{} structure

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

So final code for build.gradle(Project: project_name) will look like this:

// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.5.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.google.gms:google-services:3.1.0' } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }

Step 4: Updating build.gradle(Module:app) file

Add following code into dependencies{}

compile 'com.google.firebase:firebase-messaging:9.0.2'

Add following at the end of the file

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

Final code for build.gradle(Module:app)

apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.exampledemo.parsaniahardik.fcmsingle" minSdkVersion 16 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.google.firebase:firebase-messaging:9.0.2' } apply plugin: 'com.google.gms.google-services'

Step 5: Creating Service Classes

Creating GettingDeviceTokenService

Create a new JAVA class named “GettingDeviceTokenService” and add below source code

import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; /** * Created by Parsania Hardik on 09-Jun-17. */ public class GettingDeviceTokenService extends FirebaseInstanceIdService { @Override public void onTokenRefresh() { String DeviceToken = FirebaseInstanceId.getInstance().getToken(); Log.d("DeviceToken ==> ", DeviceToken); } }

In this service, we will get device token.

Creating NotificationService

Create a new JAVA class named “NotificationService” and add below source code

import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.text.Html; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Parsania Hardik on 09-Jun-17. */ public class NotificationService extends FirebaseMessagingService { public static int NOTIFICATION_ID = 1; @Override public void onMessageReceived(RemoteMessage remoteMessage) { //Call method to generate notification if (remoteMessage.getData().size() > 0) { Log.e("dataa", "Data Payload: " + remoteMessage.getData().toString()); try { JSONObject jsonObject = new JSONObject(remoteMessage.getData().toString()); JSONObject dataObject = jsonObject.getJSONObject("data"); String imageURL = dataObject.getString("image"); String title = dataObject.getString("title"); String message = dataObject.getString("message"); if(imageURL.equals("no")){ generateNotification( message); }else { Bitmap bitmap = getBitmapFromURL(imageURL); notificationWithImage(bitmap, title, message); } } catch (Exception e) { Log.e("exc", "Exception: " + e.getMessage()); } } } private void generateNotification( String message) { Intent intent = new Intent(this, GotNotificationActivity.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 mNotifyBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Firebase Cloud or Push Notification") .setContentText(message) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (NOTIFICATION_ID > 1073741824) { NOTIFICATION_ID = 0; } notificationManager.notify(NOTIFICATION_ID++ , mNotifyBuilder.build()); } private void notificationWithImage(Bitmap bitmap, String title, String message) { Intent intent = new Intent(this, GotNotificationActivity.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.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(); bigPictureStyle.setBigContentTitle(title); bigPictureStyle.setSummaryText(Html.fromHtml(message).toString()); bigPictureStyle.bigPicture(bitmap); NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this) .setAutoCancel(true) .setContentTitle(title) .setContentIntent(pendingIntent) .setSound(defaultSoundUri) .setStyle(bigPictureStyle) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher)) .setContentText(message); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (NOTIFICATION_ID > 1073741824) { NOTIFICATION_ID = 0; } notificationManager.notify(NOTIFICATION_ID++ , mNotifyBuilder.build()); } public Bitmap getBitmapFromURL(String strURL) { try { URL url = new URL(strURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { e.printStackTrace(); return null; } } }

Description of NotificationService

remoteMessage.getData().toString() will give us JSON data as following

{ data: { "image":"http:\/\/demonuts.com\/Demonuts\/JsonTest\/Tennis\/uploadedFiles\/popey.jpg", "title":"weeee", "message":"asss" } }

Following source code will parse above JSON data

JSONObject jsonObject = new JSONObject(remoteMessage.getData().toString()); JSONObject dataObject = jsonObject.getJSONObject("data"); String imageURL = dataObject.getString("image"); String title = dataObject.getString("title"); String message = dataObject.getString("message");

Now following source will decide whether user has sent image with notification or not.

if(imageURL.equals("no")){ generateNotification( message); }else { Bitmap bitmap = getBitmapFromURL(imageURL); notificationWithImage(bitmap, title, message); }

If image is not sent, then generateNotification() will be run.

Otherwise notificationWithImage() will be run.

getBitmapFromURL() method will give us bitmap of image(Popey Image.)

Now consider below source code

Intent intent = new Intent(this, GotNotificationActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

Above code will decide which activity to open when user clicks on Push Notification.

Here GotNotificationActivity will be open. So let’s create GotNotificationActivity.

Create a new activity named GotNotificationActivity and update activity_got_notification.xml as follow:

<?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" tools:context="com.exampledemo.parsaniahardik.fcmsingle.GotNotificationActivity"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:textColor="#000" android:textSize="20sp" android:text="I opened when you clicked on Notification! "/> </RelativeLayout>

Developing Server Side(PHP) script to send firebase push notification

Create a new PHP file and name it sendSingleFCM.php

Add below source code into it

<?php if($_SERVER['REQUEST_METHOD']=='POST'){ // echo $_SERVER["DOCUMENT_ROOT"]; // /home1/demonuts/public_html //including the database connection file //include_once("config.php"); $serverAPIKey = $_POST['serverapi']; define('FIREBASE_SERVER_KEY', $serverAPIKey); // echo FIREBASE_SERVER_KEY;exit; $selection = $_POST['isImage']; // echo $title.$selection;exit; //first check if the push has an image with it if( $_POST["isImage"] == "Yes" ){ $serverAPIKey = $_POST['serverapi']; $reg_token= $_POST['token']; $title= $_POST['title']; $message= $_POST['message']; $image= "http://demonuts.com/Demonuts/JsonTest/Tennis/uploadedFiles/popey.jpg"; }else{ //if the push don't have an image give null in place of image $serverAPIKey = $_POST['serverapi']; $reg_token= $_POST['token']; $title= $_POST['title']; $message= $_POST['message']; $image= "no"; } //firebase server url to send the curl request $url = 'https://fcm.googleapis.com/fcm/send'; //building headers for the request $headers = array( 'Authorization: key='. FIREBASE_SERVER_KEY, 'Content-Type: application/json' ); //Initializing curl to open a connection $ch = curl_init(); //Setting the curl url curl_setopt($ch, CURLOPT_URL, $url); //setting the method as post curl_setopt($ch, CURLOPT_POST, true); //adding headers curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //disabling ssl support curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $gcmRegIds = array($reg_token); // $messagearray = array("message" => $message , "title" => $title , "image" => $image); $messagearray = array(); $messagearray['data']['title'] = $title; $messagearray['data']['message'] = $message; $messagearray['data']['image'] = $image; //adding the fields in json format $fields = array( 'registration_ids' => $gcmRegIds, 'data' => $messagearray, ); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); //finally executing the curl request $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } header("Location: http://www.demonuts.com/Demonuts/JsonTest/Tennis/sendSingleFCM.php"); // exit(); //Now close the connection curl_close($ch); //and return the result return $result; } else{ //echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") ); } ?> <html> <head> <title>DemoNuts Firebase Cloud Messaging (FCM) Server in PHP</title> <style type="text/css"> #submit { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } #navigation { position: absolute; /*or fixed*/ right: 0px; margin-right: 270px; } .large { font-size: 14pt; height: 40px; } </style> </head> <body> <div id="navigation" style=" height: 600px ; width : 300px ;"> </div> <h1>Firebase Cloud Messaging (FCM) Server in PHP</h1> <form method="post" action="sendSingleFCM.php"> <h3>FIREBASE SERVER KEY</h3> <div> <input type="text" class="large" name="serverapi" size="55" placeholder="Enter Your Server KEY"></textarea> </div> <h3>DEVICE TOKEN OR REG.ID</h3> <div> <input class="large" name="token" size="55" placeholder="Enter Device Token or Reg.ID"></textarea> </div> <h3>Message</h3> <div> <textarea rows="6" name="message" cols="63" placeholder="Message to transmit via FCM"></textarea> </div> <h3>Title</h3> <div> <input class="large" name="title" size="55" placeholder="Title to transmit via FCM"></textarea> </div> <h3> Include Image? </h3> <input type="radio" name="isImage" id="no" value="Yes" checked/>Yes <input type="radio" name="isImage" id="no" value="No">No<br> <input type="submit" name="submit" value="Go Go Go...!" id="submit" /><br> </form> <p><h3><?php echo $pushStatus; ?></h3></p> </body> </html>

I have save above file here in mu server: http://demonuts.com/Demonuts/JsonTest/Tennis/sendSingleFCM.php

Upgrade above file where there is a code like

header(“Location: http://demonuts.com/Demonuts/JsonTest/Tennis/sendSingleFCM.php”)

with your server path or localhost path.

Testing your push notification without creating PHP Script

If you want to send push notification directly to your android device, then go to https://demonuts.com/Demonuts/JsonTest/Tennis/sendSingleFCM.php

Fill required details (Firebase Server Key, Device Token etc.) and click on the Go Go Go button.

Use comment section to give your review or to ask any question.

So all for Android firebase push notification Android Studio programmatically example tutorial. Thank you.

2. Send FCM Messages push notification to multiple devices android

Hi Android geeks. Android firebase push notification tutorial for multiple devices is here.

In this Android firebase push notification tutorial, we will send push notification to single or multiple devices from server(PHP-MySQL.)

This Android firebase push notification is developed using Android Studio and JAVA.

First, check the output of Android firebase push notification example then we will develop it.

Step 1: Create a new project in Android Studio.

A new Android Studio project with empty activity is required for this project. So create it first.

Step 2: Working with Firebase Console

Following video will guide you to develop app in firebase console.

Learning Easy steps of firebase console video

Go to https://firebase.google.com/ and sign in to your google account. Click on Add Project and give project name and country. Click on CREATE PROJECT button. After project is created, click on Add firebase to your Android app button. Give your Android package name and click on Register App button. Click on Download google-services.json button. Move your downloaded JSON file into app folder of your android project as shown in the video.

Step3:Changing build.gradle(Project: project_name) file:

Add following in dependencies{} structure

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

So last source code for build.gradle(Project: project_name) is:

// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.5.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.google.gms:google-services:3.1.0' } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }

Step4:Changing build.gradle(Module:app) file

Copy below into dependencies{}

apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.exampledemo.parsaniahardik.fcmsingle" minSdkVersion 16 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.google.firebase:firebase-messaging:9.0.2' } apply plugin: 'com.google.gms.google-services'

Step 5: Developing Service Classes

Developing GettingDeviceTokenService

Make a new JAVA class named “GettingDeviceTokenService” and copy following

import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; /** * Created by Parsania Hardik on 09-Jun-17. */ public class GettingDeviceTokenService extends FirebaseInstanceIdService { @Override public void onTokenRefresh() { String DeviceToken = FirebaseInstanceId.getInstance().getToken(); Log.d("DeviceToken ==> ", DeviceToken); } }

Device token is found in this service.

Developing NotificationService

Create a new JAVA class named “NotificationService” and add below source code

import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.text.Html; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Parsania Hardik on 09-Jun-17. */ public class NotificationService extends FirebaseMessagingService { public static int NOTIFICATION_ID = 1; @Override public void onMessageReceived(RemoteMessage remoteMessage) { //Call method to generate notification if (remoteMessage.getData().size() > 0) { Log.e("dataa", "Data Payload: " + remoteMessage.getData().toString()); try { JSONObject jsonObject = new JSONObject(remoteMessage.getData().toString()); JSONObject dataObject = jsonObject.getJSONObject("data"); String imageURL = dataObject.getString("image"); String title = dataObject.getString("title"); String message = dataObject.getString("message"); if(imageURL.equals("no")){ generateNotification( message); }else { Bitmap bitmap = getBitmapFromURL(imageURL); notificationWithImage(bitmap, title, message); } } catch (Exception e) { Log.e("exc", "Exception: " + e.getMessage()); } } } private void generateNotification( String message) { Intent intent = new Intent(this, GotNotificationActivity.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 mNotifyBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Firebase Cloud or Push Notification") .setContentText(message) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (NOTIFICATION_ID > 1073741824) { NOTIFICATION_ID = 0; } notificationManager.notify(NOTIFICATION_ID++ , mNotifyBuilder.build()); } private void notificationWithImage(Bitmap bitmap, String title, String message) { Intent intent = new Intent(this, GotNotificationActivity.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.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(); bigPictureStyle.setBigContentTitle(title); bigPictureStyle.setSummaryText(Html.fromHtml(message).toString()); bigPictureStyle.bigPicture(bitmap); NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this) .setAutoCancel(true) .setContentTitle(title) .setContentIntent(pendingIntent) .setSound(defaultSoundUri) .setStyle(bigPictureStyle) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher)) .setContentText(message); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (NOTIFICATION_ID > 1073741824) { NOTIFICATION_ID = 0; } notificationManager.notify(NOTIFICATION_ID++ , mNotifyBuilder.build()); } public Bitmap getBitmapFromURL(String strURL) { try { URL url = new URL(strURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { e.printStackTrace(); return null; } } }

Description of NotificationService

remoteMessage.getData().toString() will give us JSON data as following

{ data: { "image":"http:\/\/demonuts.com\/Demonuts\/JsonTest\/Tennis\/uploadedFiles\/popey.jpg", "title":"weeee", "message":"asss" } }

Following source code will parse above JSON data

JSONObject jsonObject = new JSONObject(remoteMessage.getData().toString()); JSONObject dataObject = jsonObject.getJSONObject("data"); String imageURL = dataObject.getString("image"); String title = dataObject.getString("title"); String message = dataObject.getString("message");

Now following source will decide whether user has sent image with notification or not.

if(imageURL.equals("no")){ generateNotification( message); }else { Bitmap bitmap = getBitmapFromURL(imageURL); notificationWithImage(bitmap, title, message); }

If image is not sent, then generateNotification() will be run.

Otherwise notificationWithImage() will be run.

getBitmapFromURL() method will give us bitmap of image(Popey Image.)

Now consider below source code

Intent intent = new Intent(this, GotNotificationActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

Above code will decide which activity to open when user clicks on Push Notification.

Here GotNotificationActivity will be open. So let’s create GotNotificationActivity.

Create a new activity named GotNotificationActivity and update activity_got_notification.xml as follow:

<?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" tools:context="com.exampledemo.parsaniahardik.fcmsingle.GotNotificationActivity"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:textColor="#000" android:textSize="20sp" android:text="I opened when you clicked on Notification! "/> </RelativeLayout>

Developing Server Side(PHP) script to send firebase push notification

Create a new PHP file and name it sendMultipleFCM.php

Add below source code into it

<?php if($_SERVER['REQUEST_METHOD']=='POST'){ // echo $_SERVER["DOCUMENT_ROOT"]; // /home1/demonuts/public_html //including the database connection file //include_once("config.php"); $serverAPIKey = $_POST['serverapi']; define('FIREBASE_SERVER_KEY', $serverAPIKey); // echo FIREBASE_SERVER_KEY;exit; $selection = $_POST['isImage']; // echo $title.$selection;exit; //first check if the push has an image with it if( $_POST["isImage"] == "Yes" ){ $serverAPIKey = $_POST['serverapi']; $reg_token= $_POST['token']; $reg_token2= $_POST['token2']; $title= $_POST['title']; $message= $_POST['message']; $image= "http://demonuts.com/Demonuts/JsonTest/Tennis/uploadedFiles/popey.jpg"; }else{ //if the push don't have an image give null in place of image $serverAPIKey = $_POST['serverapi']; $reg_token= $_POST['token']; $reg_token2= $_POST['token2']; $title= $_POST['title']; $message= $_POST['message']; $image= "no"; } //firebase server url to send the curl request $url = 'https://fcm.googleapis.com/fcm/send'; //building headers for the request $headers = array( 'Authorization: key='. FIREBASE_SERVER_KEY, 'Content-Type: application/json' ); //Initializing curl to open a connection $ch = curl_init(); //Setting the curl url curl_setopt($ch, CURLOPT_URL, $url); //setting the method as post curl_setopt($ch, CURLOPT_POST, true); //adding headers curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //disabling ssl support curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $gcmRegIds = array($reg_token,$reg_token2); // $gcmRegIds = array($reg_token); // print_r($gcmRegIds);exit; // $messagearray = array("message" => $message , "title" => $title , "image" => $image); $messagearray = array(); $messagearray['data']['title'] = $title; $messagearray['data']['message'] = $message; $messagearray['data']['image'] = $image; //adding the fields in json format $fields = array( 'registration_ids' => $gcmRegIds, 'data' => $messagearray, ); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); //finally executing the curl request $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } header("Location: http://www.demonuts.com/Demonuts/JsonTest/Tennis/sendMultipleFCM.php"); // exit(); //Now close the connection curl_close($ch); //and return the result return $result; } else{ //echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") ); } ?> <html> <head> <title>DemoNuts Firebase Cloud Messaging (FCM) Server in PHP</title> <style type="text/css"> #submit { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } #navigation { position: absolute; /*or fixed*/ right: 0px; margin-right: 270px; } .large { font-size: 14pt; height: 40px; } </style> </head> <body> <div id="navigation" style=" height: 600px ; width : 300px ;"> </div> <h1>Firebase Cloud Messaging (FCM) Server in PHP</h1> <form method="post" action="sendMultipleFCM.php"> <h3>FIREBASE SERVER KEY</h3> <div> <input type="text" class="large" name="serverapi" size="55" placeholder="Enter Your Server KEY"></textarea> </div> <h3>DEVICE TOKEN OR REG.ID</h3> <div> <input class="large" name="token" size="55" placeholder="Enter Device Token or Reg.ID"></textarea> </div> <h3>DEVICE TOKEN OR REG.ID-2</h3> <div> <input class="large" name="token2" size="55" placeholder="Enter Device Token or Reg.ID-2"></textarea> </div> <h3>Message</h3> <div> <textarea rows="6" name="message" cols="63" placeholder="Message to transmit via FCM"></textarea> </div> <h3>Title</h3> <div> <input class="large" name="title" size="55" placeholder="Title to transmit via FCM"></textarea> </div> <h3> Include Image? </h3> <input type="radio" name="isImage" id="no" value="Yes" checked/>Yes <input type="radio" name="isImage" id="no" value="No">No<br> <input type="submit" name="submit" value="Go Go Go...!" id="submit" /><br> </form> <p><h3><?php echo $pushStatus; ?></h3></p> </body> </html>

I have save above file here in my server: http://demonuts.com/Demonuts/JsonTest/Tennis/sendMultipleFCM.php

Upgrade above file where there is a code like

header(“Location: http://demonuts.com/Demonuts/JsonTest/Tennis/sendMultipleFCM.php”)

with your server path or localhost path.

Testing your push notification without creating PHP Script

If you want to send push notification directly to your android device, then go to

http://www.demonuts.com/Demonuts/JsonTest/Tennis/sendMultipleFCM.php

Fill required details (Firebase Server Key, Device Tokens etc.) and click on the Go Go Go button.

Provide two device tokens to get notifications on them.

You can also enter only device token and keep another empty. Of course Notification will be sent to only one device.

Use comment section to give your review or to ask any question.

So all for Android firebase push notification to multiple devices programmatically example tutorial. Thank you.

3. Firebase cloud messaging Android Tutorial

You will need to work with Android Firebase Cloud Messaging example(FCM) for adding push notifications in android app.

Firebase Cloud Messaging Android Studio Tutorial guide you to integrate firebase push notification(FCM) in android studio.

In this Firebase Cloud Messaging Android Studio Tutorial, we will send notification from firebase console.

First, check output then we will develop Firebase Cloud Messaging Android Studio example(FCM).

Step 1: Create a new project in Android Studio.

If you select default activity as an empty activity while creating new project in android studio, it will be great choice.

Step 2: Creating app in Firebase Console

I have developed a video about how to make an app in the firebase console.

Quick steps of above video

Go to https://firebase.google.com/ and sign in to your google account. Click on Add Project and give project name and country. Click on CREATE PROJECT button. After project is created, click on Add firebase to your Android app button. Give your Android package name and click on Register App button. Click on Download google-services.json button. Move your downloaded JSON file into app folder of your android project as shown in the video.

Step 3: Updating build.gradle(Project: project_name) file:

we need to add following in dependencies{} structure

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

So final code for build.gradle(Project: project_name) will look like this:

// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.5.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.google.gms:google-services:3.1.0' } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }

Step 4: Updating build.gradle(Module:app) file

Add following code into dependencies{}

compile 'com.google.firebase:firebase-messaging:9.0.2'

Add following at the end of the file

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

Final code for build.gradle(Module:app)

apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.exampledemo.parsaniahardik.simplefcm" minSdkVersion 16 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.google.firebase:firebase-messaging:9.0.2' } apply plugin: 'com.google.gms.google-services'

Step 5: Creating Service Classes

Creating GettingDeviceTokenService

Create a new JAVA class named “GettingDeviceTokenService” and add below source code

import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; /** * Created by Parsania Hardik on 09-Jun-17. */ public class GettingDeviceTokenService extends FirebaseInstanceIdService { @Override public void onTokenRefresh() { String DeviceToken = FirebaseInstanceId.getInstance().getToken(); Log.d("DeviceToken ==> ", DeviceToken); } }

In this service, we will get device token.

Creating NotificationService

Create a new JAVA class named “NotificationService” and add below source code

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; /** * Created by Parsania Hardik on 09-Jun-17. */ public class NotificationService extends FirebaseMessagingService { public static int NOTIFICATION_ID = 1; @Override public void onMessageReceived(RemoteMessage remoteMessage) { //Call method to generate notification generateNotification(remoteMessage.getNotification().getBody()); } private void generateNotification(String messageBody) { 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 mNotifyBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Firebase Cloud or Push Notification") .setContentText(messageBody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (NOTIFICATION_ID > 1073741824) { NOTIFICATION_ID = 0; } notificationManager.notify(NOTIFICATION_ID++ , mNotifyBuilder.build()); } }

We will receive message in this service.

You can also control title,icon, vibration, message tone etc. in this service.

Step 6: Updating AndroidManifest.xml

Add internet permission in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Add services into <application> … </application> tags

<service android:name=".NotificationService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> <service android:name=".GettingDeviceTokenService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service>

Final code for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.exampledemo.parsaniahardik.simplefcm"> <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=".NotificationService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> <service android:name=".GettingDeviceTokenService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service> </application> </manifest>

Step 7: Time to getting Notification

As you have seen in output video at the starting of the tutorial, get device token from logcat.

Now go to the firebase console and select your project.

Click on Notification from left menu bar.

from bar. Now type your message and select single device in Target.

Put device token into the FCM registration token field and click on Send Message -> Send

and…. ya you have push notification same as getting in WhatsApp or other app.

Feel free ask your questions and queries in comment section.

So all for firebase cloud messaging Android Studio programmatically example tutorial. Thank you.