Home > Android Notifications using Firebase Cloud Messaging FCM & PHP

Android Notifications using Firebase Cloud Messaging FCM & PHP

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably delivery messages and notifications at no cost. FCM is completely free and there are no limitations.

In this article we learn the features of firebase cloud messaging by building a simple app. We’ll also learn how to integrate firebase to your backend, so that you can send the messages from your server.

1-(A) Set Up a Firebase Firebase Cloud Messaging for beginning

(a). Go to firebase console https://console.firebase.google.com/

After you gain access to the console you can start by creating your New project.

  • Firebase console

Click on Add Project

(b). Fill Project Name I use FCMNotification & select country I select India. After that click on CREATE PROJECT then Choose App type (I choose Android)

  • Create Project
  • Choose app type

(c). Give the package name of your project (My is com.amisun.fcmnotification) & SHA1 in which you are going to integrate the Firebase. After filling project details press on REGISTER APP button. Then Show next dialog. Here download google-services.json After downloading click CONTINUE button. Then show a dialog that contain information about integration read this and press FINISH button.

  • Project Detail screen
  • Download google-services.json
  • Integration info

(d).After successfully add project in dashboard listed here.

  • Dashboard Console

Completed Set Up a Firebase Firebase Cloud Messaging for beginning


1-(B) Set Up a Firebase Firebase Cloud Messaging for Existing Project

(a). Go to firebase console https://console.firebase.google.com/

After you gain access to the Dashboard console. Open existing project (I choose FCMNotification)

  • Firebase console

After opening project press on Add another app & choose app type (I choose Android )

  • App list screen
  • Choose app type

(b). Give the package name of your project (My is com.isoftinc.aukfly) & SHA1 in which you are going to integrate the Firebase. After filling project details press REGISTER APP. Then Show next dialog. Here download google-services.json After downloading click CONTINUE button. Then show a dialog that contain information about integration read this and press FINISH button.

  • Project Detail screen
  • Download google-services.json
  • Integration info

(c).After successfully add project in dashboard listed here.

  • Dashboard Console

2. Getting cloud messaging server key for PHP

(a.) Go to firebase dashboard --> Choose project (My is FCM Notification) --> Choose App package name (My is com.amisun.fcmnotification) & Click 3 dots line (right top) button & select setting menu option.

  • Dashboard Console
  • Created App list
  • Choose setting menu

(b.) In App setting screen 5 tab (a) GENERAL, (b) CLOUD MESSAGING, (c) ANALYTICS, (d) ACCOUNT LINKING, (e) SERVICE ACCOUNTS.

  • Dashboard Console

select CLOUD MESSAGING menu tab

  • Cloud Messaging server key

In Cloud Messaging showing 2 key (a) Server key, (b) Legacy Server key

Legacy Server key is use when send notification from backend side. Note down this key.


3. Creating Android Project

1. Create a new project in Android Studio from File ? New Project and fill the project details.While filling the project details, use the same package name which you give in firebase console. In my case I am using :

app name = FCMNotification &

package name = com.amisun.fcmnotification

2. Add Downloaded google-services.json file into FCMNotification/app/ directory

3. Now open the build.gradle located in project’s home directory and add firebase dependency.

									
dependencies { classpath 'com.android.tools.build:gradle:2.1.3' classpath 'com.google.gms:google-services:3.0.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }

4. Open app/build.gradle and add firebase messaging dependency. At the bottom of the file, add apply plugin: 'com.google.gms.google-services' & dependencies 'com.google.firebase:firebase-messaging:9.4.0'

									
android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.amisun.fcmnotification" minSdkVersion 15 targetSdkVersion 25 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:25.2.0' compile 'com.google.firebase:firebase-messaging:9.4.0' } apply plugin: 'com.google.gms.google-services'

5. Create a shared preferences Class for stores & get the device registration token

									
package com.amisun.fcmnotification; import android.content.Context; import android.content.SharedPreferences; public class SharedPrefManager { private static final String SHARED_PREF_NAME = "FCMSharedPref"; private static final String TAG_TOKEN = "devicetoken"; private static SharedPrefManager mInstance; private static Context mCtx; private SharedPrefManager(Context context) { mCtx = context; } public static synchronized SharedPrefManager getInstance(Context context) { if (mInstance == null) { mInstance = new SharedPrefManager(context); } return mInstance; } //this method will save the device token to shared preferences public boolean saveDeviceToken(String token){ SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TAG_TOKEN, token); editor.apply(); return true; } //this method will fetch the device token from shared preferences public String getDeviceToken(){ SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return sharedPreferences.getString(TAG_TOKEN, null); } }

6. Create a class named MyFirebaseInstanceIDService.java . This class receives the firebase registration id which will be unique to each app. This registration id is needed when you want to send message to a single device. You can send this token to your server app to send notification to devices later.

									
package com.amisun.fcmnotification; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "FCMFirebaseIIDService"; @Override public void onTokenRefresh() { String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); storeToken(refreshedToken); } private void storeToken(String token) { //saving the token on shared preferences SharedPrefManager.getInstance(getApplicationContext()).saveDeviceToken(token); // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(MainActivity.PUSH_NOTIFICATION); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } }

onTokenRefresh() method will be called whenever there is a change in firebase registration id.

storeToken() stores the registration id in shared preferences.

7. Create another class named MyFirebaseMessagingService.java. This class receives the firebase messages into onMessageReceived() method.

									
package com.amisun.fcmnotification; import android.content.Intent; import android.util.Log; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import org.json.JSONException; import org.json.JSONObject; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMsgService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { if (remoteMessage.getData().size() > 0) { Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString()); try { JSONObject json = new JSONObject(remoteMessage.getData().toString()); sendPushNotification(json); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } } //this method will display the notification //We are passing the JSONObject that is received from //firebase cloud messaging private void sendPushNotification(JSONObject json) { //optionally we can display the json into log Log.e(TAG, "Notification JSON " + json.toString()); try { //getting the json data JSONObject data = json.getJSONObject("data"); //parsing json data String title = data.getString("title"); String message = data.getString("message"); String imageUrl = data.getString("image"); //creating MyNotificationManager object MyNotificationManager mNotificationManager = new MyNotificationManager(getApplicationContext()); //creating an intent for the notification Intent intent = new Intent(getApplicationContext(), MainActivity.class); //if there is no image if(imageUrl.equals("null")){ //displaying small notification mNotificationManager.showSmallNotification(title, message, intent); }else{ //if there is an image //displaying a big notification mNotificationManager.showBigNotification(title, message, imageUrl, intent); } } catch (JSONException e) { Log.e(TAG, "Json Exception: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } }

8. Create a class named MyNotificationManager.java . This class contains necessary functions required to show the message (with title, message, image or with title, message) in notification tray.

									
package com.amisun.fcmnotification; import android.app.Notification; 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.support.v4.app.NotificationCompat; import android.text.Html; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Random; public class MyNotificationManager { public static final int ID_BIG_NOTIFICATION = 234; public static final int ID_SMALL_NOTIFICATION = 235; private Context mCtx; public MyNotificationManager(Context mCtx) { this.mCtx = mCtx; } //the method will show a big notification with an image //parameters are title for message title, message for message text, url of the big image and an intent that will open //when you will tap on the notification public void showBigNotification(String title, String message, String url, Intent intent) { PendingIntent resultPendingIntent = PendingIntent.getActivity( mCtx, ID_BIG_NOTIFICATION, intent, PendingIntent.FLAG_UPDATE_CURRENT ); NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(); bigPictureStyle.setBigContentTitle(title); bigPictureStyle.setSummaryText(Html.fromHtml(message).toString()); bigPictureStyle.bigPicture(getBitmapFromURL(url)); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx); Notification notification; notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0) .setAutoCancel(true) .setContentIntent(resultPendingIntent) .setContentTitle(title) .setStyle(bigPictureStyle) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(),R.mipmap.ic_launcher)) .setContentText(message) .build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; Random random = new Random(); int m = random.nextInt(9999 - 1000) + 1000; NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(m, notification); } //the method will show a small notification //parameters are title for message title, message for message text and an intent that will open //when you will tap on the notification public void showSmallNotification(String title, String message, Intent intent) { PendingIntent resultPendingIntent = PendingIntent.getActivity( mCtx, ID_SMALL_NOTIFICATION, intent, PendingIntent.FLAG_UPDATE_CURRENT ); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx); Notification notification; notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher).setTicker(title).setWhen(0) .setAutoCancel(true) .setContentIntent(resultPendingIntent) .setContentTitle(title) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.mipmap.ic_launcher)) .setContentText(message) .build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(ID_SMALL_NOTIFICATION, notification); } //The method will return Bitmap from an image URL private 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; } } }

9. Open AndroidManifest.xml and add the two firebase services MyFirebaseMessagingService and MyFirebaseInstanceIDService under application tag.

									
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.amisun.fcmnotification"> <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> <!--<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />--> <service android:name="com.amisun.fcmnotification.MyFirebaseInstanceIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service> <service android:name="com.amisun.fcmnotification.MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> </application> </manifest>

10. Open MainActivity.java and do the below necessary changes. Here in onResume() method we are registering the broadcast receivers.

displayDeviceRegId() fetches the firebase registration device token from shared preferences and displays it on the screen. This is just for your references, we don’t use the registration device token any where in the app.

									
package com.amisun.fcmnotification; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private BroadcastReceiver mRegistrationBroadcastReceiver; public static final String PUSH_NOTIFICATION = "pushNotification"; TextView txtDeviceToken; private String deviceToken; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtDeviceToken = (TextView)findViewById(R.id.txtDeviceToken); deviceToken = SharedPrefManager.getInstance(MainActivity.this).getDeviceToken(); if(deviceToken != null){ displayDeviceRegId(); } mRegistrationBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase(PUSH_NOTIFICATION)){ displayDeviceRegId(); } } }; } // Fetches registered fcm device token from shared preferences // and displays on the screen private void displayDeviceRegId() { deviceToken = SharedPrefManager.getInstance(MainActivity.this).getDeviceToken(); Log.e("FCM Device token",deviceToken); Toast.makeText(getApplicationContext(), "Push notification: " + deviceToken, Toast.LENGTH_LONG).show(); txtDeviceToken.setText(deviceToken); } @Override protected void onResume() { super.onResume(); // register new push message receiver // by doing this, the activity will be notified each time a new message arrives LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(PUSH_NOTIFICATION)); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); super.onPause(); } }

11. Run app

  • Device screen
  • Studio logcat

Note down FCM Device token or copy from logcat and save on notepad. This device token use backend side during send push notification.


4. Sending push notification from Firebase Console

1. Now we’ll send the first message from firebase console. Go to firebase console --> select project (In my case FCMNotification) and click on Notifications in left menu. You will get an interface where you can type the message, select the targeting and send the message.

  • Dashboard screen
  • Project screen
  • Notification screen

In Notification screen type sending message & select package. After this press SEND MESSAGE

2. Out put Notification in device from Firebase console

  • Device screen

5. Sending push notification from Server side

Let’s create a simple PHP project to send the messages from backend. I am assuming you are having basic knowledge of PHP .

1. Obtaining your Firebase Server API Key

Firebase provides Server API Key to identify your firebase app. To obtain your Server API Key, goto firebase console, select the project and goto settings, select Cloud Messaging tab and copy your Server key. Follow step (2. Getting cloud messaging server key for PHP)

2. Goto your WAMP or server directory and create new folder named firebase inside htdocs or www or public_html.

3. Create a file named firebase.php and add the below code. This class contains necessary functions to send message to firebase api by making a CURL request. There i use Firebase Server API Key in FIREBASE_API_KEY constant

									
<?php class Firebase { public function send($registration_ids, $message) { $fields = array( 'registration_ids' => $registration_ids, 'data' => $message, ); return $this->sendPushNotification($fields); } /* * This function will make the actuall curl request to firebase server * and then the message is sent */ private function sendPushNotification($fields) { //importing the constant files //require_once 'Config.php'; //defined a new constant for firebase api key define('FIREBASE_API_KEY', 'AIzaSyD-dxxe2kAYExVx-Uzjxs89UAlsWwEAjTk'); //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_API_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); //adding the fields in json format 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)); } //Now close the connection curl_close($ch); //and return the result return $result; } } ?>

4. Create a file named sendNotification.php This class prepares and send push notification .

									
<?php require_once 'Firebase.php'; // paste here getting fcm registration device token $devicetoken [] = "dYbGw47Vshs:APA91bGJflBAmQO8lfFN9ca-IGbqvLQbCr0JvBVgK31NdQIBiFvHrrPyYEE6IFFoCRymI8Z7aqTQ9a2icRZusW0vHFqzSVyksVx3uIeh9kFGl6CTcXEEORJHV9qBu48lR2KaZTuZ3FrM"; // create array that contains notification details $res = array(); //push title, message, & image url for big notification like as below $res['data']['title'] = "FCM Notification"; $res['data']['message'] = "Testing message"; $res['data']['image'] = "http://www.amisungroups.com/developer/fcmNotification/android_banner.jpg"; /* //push title, message for small notification like as below $res['data']['title'] = "FCM Demo"; $res['data']['message'] = "Testing message";*/ //creating firebase class object $firebase = new Firebase(); //sending push notification and displaying result echo $firebase->send($devicetoken, $res); ?>

Run sendNotification.php file in browser then out put as below.

  • Device output screen
  • Browser output screen

I hope this article give you very good overview of Push Notifications using Firebase Cloud Messaging FCM & PHP. Feel free to ask any queries / doubts in comments section below.



Dheerendra Singh

Dheerendra Singh is a Mobile Developer(Android) & Web Developer(PHP) of Amisun IT Solutions, Master degree in Computer Science.


About Us

Amisun IT Solutions is an expert Software Development Company giving complete IT arrangements and going about as a seaward improvement community for abroad advancement firms.

We are an imaginative organization, situated in India that gives a progression of Web-based programming applications that have helped clients make fruitful online activities.

Our group of forward masterminds and reforming individuals tries to furnish you with the best of arrangements with flawlessness second to none. Our key concentration is dependably to furnish you with solid arrangements which are precisely planned and planned with stringent quality principles. ...   

Read more

Address

Shoppers Square Mall Shop No. 17 & 18, First Floor,
Shoppers Square Mall, Budhh Prakash Garg Marg, Block 14, Sector 10,
Raj Nagar, Ghaziabad, Uttar Pradesh 201002
P: (+91) 9899776200, (+91) 9899773200