Hey guys, so here I am back with another Firebase Cloud Messaging tutorial. You all know about Firebase Cloud Messaging, it is a push notification service and we can use it to send messages to our app users.
This method is deprecated. Follow the updated tutorial here:
Android Push Notification Tutorial using Firebase Cloud Messaging
So here are the points that we are going to cover with this Firebase Cloud Messaging Tutorial.
Table of Contents
- 1 Firebase Cloud Messaging for Android Video Series
- 2 Integrating Firebase Cloud Messaging in Android Project
- 3 Displaying Push Notification
- 4 Building Web Services Part 1
- 5 Storing Token to MySQL Database
- 6 Building Web Services Part 2
- 7 Making Send Notification Option in App
- 8 Firebase Cloud Messaging Source Code
Firebase Cloud Messaging for Android Video Series
- If you want to go with a video tutorial explaining everything about Firebase Cloud Messaging then go through the below playlist.
Integrating Firebase Cloud Messaging in Android Project
Creating a new Android Project
- With Android Studio 2.2 it is really easy to integrate firebase in your project.
- First create a new Android Studio Project with an Empty Activity.
- Once your project is loaded click on firebase from the tools menu.
- After clicking on Firebase an assistant will open showing all the available firebase features.
- As you can see in the above images we have all the Firebase Services. But at this time we care about Cloud Messaging. So click on Cloud Messaging.Â
Setting Up Firebase Cloud Messaging
- You will see a link saying Set Up Firebase Cloud Messaging. Click on it.
- Now you will see all the steps required to Set up Firebase Cloud Messaging in the project.
#1 Connect Your App to Firebase
- Simply click on the Connect to Firebase button. It will start a connect dialog.
- Here you can create a new Project on Firebase, as I am creating a project named FcmSimplifiedCoding (See the below screenshot). Or you can also select an existing firebase project.
- Now simply click on Connect to Firebase. And wait for a few seconds. And you will see the following message in the assistant.
- So step number 1 is completed successfully. Now lets move ahead.
#2Â Add FCM to Your App
- Again click on the button Add FCM to your app and you will see a dialog box.
- Click on Accept Changes. And firebase is setup in your project now.
Generating Device Token
- Every device generates a unique token to receive notifications. And for this we have to create a class that will extend the class FirebaseInstanceIdService. This part is same as we did in the previous Firebase Cloud Messaging Tutorial.
- So create a class named MyFirebaseInstanceIDService.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package net.simplifiedcoding.firebasecloudmessaging; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; /** * Created by Belal on 03/11/16. */ //Class extending FirebaseInstanceIdService public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIIDService"; @Override public void onTokenRefresh() { //Getting registration token String refreshedToken = FirebaseInstanceId.getInstance().getToken(); //Displaying token on logcat Log.d(TAG, "Refreshed token: " + refreshedToken); //calling the method store token and passing token storeToken(refreshedToken); } private void storeToken(String token) { //we will save the token in sharedpreferences later } } |
- As this is a service we need to define this class inside AndroidManifest.xml. So come inside AndroidManifest.xml and write the following code inside application tag.
1 2 3 4 5 6 7 8 |
<service android:name=".MyFirebaseInstanceIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service> |
Storing Device Token
Saving Token
- First we will store the generated token in SharedPreferences.
- So, for managing the SharedPreferences we will create a class in Singleton Pattern.
- Create a class named SharedPrefManager.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package net.simplifiedcoding.firebasecloudmessaging; import android.content.Context; import android.content.SharedPreferences; /** * Created by Belal on 03/11/16. */ public class SharedPrefManager { private static final String SHARED_PREF_NAME = "FCMSharedPref"; private static final String TAG_TOKEN = "tagtoken"; 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); } } |
- Now to save the token generated with the FirebaseInstanceIdService we will call the method of the above class.
- So you need to modify the class MyFirebaseInstanceIDService.java as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package net.simplifiedcoding.firebasecloudmessaging; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; /** * Created by Belal on 03/11/16. */ public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIIDService"; @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); } } |
Displaying Token
- Though this part is not necessary but just to make sure the token is generated and saved in the SharedPreferences, we can display the token.
- For this come inside activity_main.xml and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?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:id="@+id/activity_main" 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="net.simplifiedcoding.firebasecloudmessaging.MainActivity"> <Button android:layout_centerVertical="true" android:text="Display Token" android:id="@+id/buttonDisplayToken" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/textViewToken" android:layout_alignParentBottom="true" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout> |
- The above code will generate the following layout.
- We have a Button and a TextView. On button click we have to display the token on the TextView. We can easily do it by using the Singleton class SharedPrefManager that we created.
- So come inside MainActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package net.simplifiedcoding.firebasecloudmessaging; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //defining views private Button buttonDisplayToken; private TextView textViewToken; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting views from xml textViewToken = (TextView) findViewById(R.id.textViewToken); buttonDisplayToken = (Button) findViewById(R.id.buttonDisplayToken); //adding listener to view buttonDisplayToken.setOnClickListener(this); } @Override public void onClick(View view) { if (view == buttonDisplayToken) { //getting token from shared preferences String token = SharedPrefManager.getInstance(this).getDeviceToken(); //if token is not null if (token != null) { //displaying the token textViewToken.setText(token); } else { //if token is null that means something wrong textViewToken.setText("Token not generated"); } } } } |
- Now just run your application. And click on the button you should see the token in the TextView.
- But if you are seeing token not generated then something is wrong. In this case try with a different emulator. Or try by uninstalling the application from your device.
- If you are getting the token, then you can move ahead.
Creating Messaging Service
- We have the device token, now we need one more class that will extend FirebaseMessagingService, this class will actually receive the notification.
- So create a new class named MyFirebaseMessagingService.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package net.simplifiedcoding.firebasecloudmessaging; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; /** * Created by Belal on 03/11/16. */ public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMsgService"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { } } |
- In the above code onMessageReceived(RemoteMessage remoteMessage) method will be called when the message is received by the push notification.
- Again we need to define this service inside AndroidManifest.xml. For this write the following xml code inside <application> tag.
1 2 3 4 5 6 7 8 |
<service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> |
- Now we need to handle the message that will be received, to display it as a notification.
Displaying Push Notification
Creating a class to Handle Push Notifications
- To show push notification we will create a class named MyNotificationManager.java. Here we will create the required method to show the notifications.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
package net.simplifiedcoding.firebasecloudmessaging; /** * Created by Belal on 03/11/16. */ 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; /** * Created by Ravi on 31/03/15. */ 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; NotificationManager notificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(ID_BIG_NOTIFICATION, 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; } } } |
- We will be using the methods showBigNotification() and showSmallNotification() to notify the user as required.
- These methods will be called from the MyFirebaseMessagingService.java class. So lets modify this class to display notification.
Displaying Notification
- Come inside MyFirebaseMessagingService.java and modify it as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
package net.simplifiedcoding.firebasecloudmessaging; 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; /** * Created by Belal on 03/11/16. */ 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()); } } } |
- We have done with the notification, but a very important thing still remaining. We have to store the token to the server. As by now, the device token is in the device only and without token we cannot use Firebase Cloud Messaging. So here comes that task of creating the web services that will store the registration token to our server.
Building Web Services Part 1
- In this phase we have to do the following tasks.
- Database Creation
- Web service to store token in database
- I will be using XAMPP, using PHP is not necessary you can use any technology you are comfortable in. I am using PHP with XAMPP. So lets start with Database Creation.
Creating Database
- Go to phpmyadmin and run the following SQL command to make the database.
1 2 3 4 5 6 7 |
CREATE TABLE `devices` ( `id` int(11) PRIMARY KEY AUTO_INCREMENT, `email` varchar(100) NOT NULL, `token` text NOT NULL ); |
- We will insert an email and device token in each row of the table. So lets move into creating php scripts.
Creating PHP Scripts
Scripts for DB Connection and DB Operation
- Again I will be doing this thing in the simplest way but in real world scenario you should follow Creating RESTful API for these tasks.
- Inside the directory htdocs (because I am using xampp) create a folder for the php scripts. I created FcmExample.
- Inside FcmExample create a file named Config.php and write the following code.
1 2 3 4 5 6 7 |
<?php define('DB_USERNAME','root'); define('DB_PASSWORD',''); define('DB_NAME','fcm'); define('DB_HOST','localhost'); |
- Create a file named DbConnect.php, in this file we will create a class to connect to our database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php //Class DbConnect class DbConnect { //Variable to store database link private $con; //Class constructor function __construct() { } //This method will connect to the database function connect() { //Including the config.php file to get the database constants include_once dirname(__FILE__) . '/Config.php'; //connecting to mysql database $this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); //Checking if any error occured while connecting if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //finally returning the connection link return $this->con; } } |
- Now create another file named DbOperation.php, in this file we will create a class to handle the database operations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
<?php class DbOperation { //Database connection link private $con; //Class constructor function __construct() { //Getting the DbConnect.php file require_once dirname(__FILE__) . '/DbConnect.php'; //Creating a DbConnect object to connect to the database $db = new DbConnect(); //Initializing our connection link of this class //by calling the method connect of DbConnect class $this->con = $db->connect(); } //storing token in database public function registerDevice($email,$token){ if(!$this->isEmailExist($email)){ $stmt = $this->con->prepare("INSERT INTO devices (email, token) VALUES (?,?) "); $stmt->bind_param("ss",$email,$token); if($stmt->execute()) return 0; //return 0 means success return 1; //return 1 means failure }else{ return 2; //returning 2 means email already exist } } //the method will check if email already exist private function isEmailexist($email){ $stmt = $this->con->prepare("SELECT id FROM devices WHERE email = ?"); $stmt->bind_param("s",$email); $stmt->execute(); $stmt->store_result(); $num_rows = $stmt->num_rows; $stmt->close(); return $num_rows > 0; } //getting all tokens to send push to all devices public function getAllTokens(){ $stmt = $this->con->prepare("SELECT token FROM devices"); $stmt->execute(); $result = $stmt->get_result(); $tokens = array(); while($token = $result->fetch_assoc()){ array_push($tokens, $token['token']); } return $tokens; } //getting a specified token to send push to selected device public function getTokenByEmail($email){ $stmt = $this->con->prepare("SELECT token FROM devices WHERE email = ?"); $stmt->bind_param("s",$email); $stmt->execute(); $result = $stmt->get_result()->fetch_assoc(); return array($result['token']); } //getting all the registered devices from database public function getAllDevices(){ $stmt = $this->con->prepare("SELECT * FROM devices"); $stmt->execute(); $result = $stmt->get_result(); return $result; } } |
Script to Store Device Token in MySQL
- To store the token to database we need one more script that will actually get the token and process it to the database. So create one more php file named RegisterDevice.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php require_once 'DbOperation.php'; $response = array(); if($_SERVER['REQUEST_METHOD']=='POST'){ $token = $_POST['token']; $email = $_POST['email']; $db = new DbOperation(); $result = $db->registerDevice($email,$token); if($result == 0){ $response['error'] = false; $response['message'] = 'Device registered successfully'; }elseif($result == 2){ $response['error'] = true; $response['message'] = 'Device already registered'; }else{ $response['error'] = true; $response['message']='Device not registered'; } }else{ $response['error']=true; $response['message']='Invalid Request...'; } echo json_encode($response); |
- Now test the script using a REST Client. I am using POSTMAN here.
- As you can see the script is working fine. But before moving ahead in Android side you need to use the host ip instead of localhost in the URL.
- For windows use ipconfig in command prompt and in terminal use ifconfig to know the IP Address. So in my case the URL to this script with the ip is.
http://192.168.1.102/FcmExample/RegisterDevice.php
Script to Fetch All the Registered Device
- As we will send the push from the android device itself. So we need to get all the registered device. For this task we need a php script that will fetch all the registered device from database.
- So create a file named GetRegisteredDevices.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php require_once 'DbOperation.php'; $db = new DbOperation(); $devices = $db->getAllDevices(); $response = array(); $response['error'] = false; $response['devices'] = array(); while($device = $devices->fetch_assoc()){ $temp = array(); $temp['id']=$device['id']; $temp['email']=$device['email']; $temp['token']=$device['token']; array_push($response['devices'],$temp); } echo json_encode($response); |
- You can check this script as well.
Storing Token to MySQL Database
- Now we send the token from SharedPreference to MySQL database. As our web service for this action is ready.
- First we will modify the activity_main.xml as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?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:id="@+id/activity_main" 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="net.simplifiedcoding.firebasecloudmessaging.MainActivity"> <EditText android:layout_above="@+id/buttonRegister" android:hint="Enter email" android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:layout_centerVertical="true" android:text="Register Device" android:id="@+id/buttonRegister" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout> |
- Now we have the layout for MainActivity as below.
- So we have an EditText and a Button. We need to put email in the EditText then click on the Button to register the device for receiving notification.
- Now to complete the functionality made the following changes in MainActivity.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
package net.simplifiedcoding.firebasecloudmessaging; import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; 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 org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //defining views private Button buttonRegister; private EditText editTextEmail; private ProgressDialog progressDialog; //URL to RegisterDevice.php private static final String URL_REGISTER_DEVICE = "http://192.168.1.102/FcmExample/RegisterDevice.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting views from xml editTextEmail = (EditText) findViewById(R.id.editTextEmail); buttonRegister = (Button) findViewById(R.id.buttonRegister); //adding listener to view buttonRegister.setOnClickListener(this); } //storing token to mysql server private void sendTokenToServer() { progressDialog = new ProgressDialog(this); progressDialog.setMessage("Registering Device..."); progressDialog.show(); final String token = SharedPrefManager.getInstance(this).getDeviceToken(); final String email = editTextEmail.getText().toString(); if (token == null) { progressDialog.dismiss(); Toast.makeText(this, "Token not generated", Toast.LENGTH_LONG).show(); return; } StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGISTER_DEVICE, new Response.Listener<String>() { @Override public void onResponse(String response) { progressDialog.dismiss(); try { JSONObject obj = new JSONObject(response); Toast.makeText(MainActivity.this, obj.getString("message"), Toast.LENGTH_LONG).show(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("email", email); params.put("token", token); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } @Override public void onClick(View view) { if (view == buttonRegister) { sendTokenToServer(); } } } |
- After this you can try running your application.
- As you can see we are getting the success message. Now check the MySQL database to ensure that token is stored.
- Yeah we got the device token in our MySQL database.
Building Web Services Part 2
- Again we need to build some more web services. So lets begin.
Building Web Service for Sending Push Notification
- Now we will build the Web Service needed to send push notification.
- We have two kinds of push notification in this project. One when we will send Push to a single device. And the other one is when we will broadcast push notification to all devices.
- But first we will configure some basic things for sending push using Firebase Cloud Messaging.
Getting Firebase Server Key
- Go to Firebase Console and inside your project settings go to cloud messaging tab.
- You will find the Cloud Messaging Server Key here, copy it.
- Now go inside the existing Config.php file and define one more constant that will store our Firebase API Key.
1 2 3 4 5 6 7 8 9 10 |
<?php define('DB_USERNAME','root'); define('DB_PASSWORD',''); define('DB_NAME','fcm'); define('DB_HOST','localhost'); //defined a new constant for firebase api key define('FIREBASE_API_KEY', 'PUT_YOUR_API_KEY_HERE'); |
Creating a class to store Push Notification
- Create a file named Push.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php class Push { //notification title private $title; //notification message private $message; //notification image url private $image; //initializing values in this constructor function __construct($title, $message, $image) { $this->title = $title; $this->message = $message; $this->image = $image; } //getting the push notification public function getPush() { $res = array(); $res['data']['title'] = $this->title; $res['data']['message'] = $this->message; $res['data']['image'] = $this->image; return $res; } } |
- The above class is very simple its only initializing the variables required for push in the constructor, and giving us back an array with the required data in getPush() method.
Creating a Separate Class for Handling cURL operation
- To send push notification we need to make http request to firebase server. And we can do it using cURL. So to handle this task create a new php file named Firebase.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<?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'; //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; } } |
Script to Send Push Notification
Sending to a Single Device
- To send push to a single device create a php script named sendSinglePush.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<?php //importing required files require_once 'DbOperation.php'; require_once 'Firebase.php'; require_once 'Push.php'; $db = new DbOperation(); $response = array(); if($_SERVER['REQUEST_METHOD']=='POST'){ //hecking the required params if(isset($_POST['title']) and isset($_POST['message']) and isset($_POST['email'])){ //creating a new push $push = null; //first check if the push has an image with it if(isset($_POST['image'])){ $push = new Push( $_POST['title'], $_POST['message'], $_POST['image'] ); }else{ //if the push don't have an image give null in place of image $push = new Push( $_POST['title'], $_POST['message'], null ); } //getting the push from push object $mPushNotification = $push->getPush(); //getting the token from database object $devicetoken = $db->getTokenByEmail($_POST['email']); //creating firebase class object $firebase = new Firebase(); //sending push notification and displaying result echo $firebase->send($devicetoken, $mPushNotification); }else{ $response['error']=true; $response['message']='Parameters missing'; } }else{ $response['error']=true; $response['message']='Invalid request'; } echo json_encode($response); |
- Now again you can test this script using POSTMAN.
- First try sending a notification without image. So we have to put only title, message and email in parameters.
- If you are getting a success then you should see the notification in your device as well.
- Now also try notification with an image. To send an image along with the message you just need to put one more parameter in the request named image and it will contain the url of the image.
- In this time you should see a notification as below in the device.
- So the push notification is working absolutely fine.
Sending to All Device
- Now the second case is when we want to broadcast message to all the register device. For this create one more php script named sendMultiplePush.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<?php //importing required files require_once 'DbOperation.php'; require_once 'Firebase.php'; require_once 'Push.php'; $db = new DbOperation(); $response = array(); if($_SERVER['REQUEST_METHOD']=='POST'){ //hecking the required params if(isset($_POST['title']) and isset($_POST['message'])) { //creating a new push $push = null; //first check if the push has an image with it if(isset($_POST['image'])){ $push = new Push( $_POST['title'], $_POST['message'], $_POST['image'] ); }else{ //if the push don't have an image give null in place of image $push = new Push( $_POST['title'], $_POST['message'], null ); } //getting the push from push object $mPushNotification = $push->getPush(); //getting the token from database object $devicetoken = $db->getAllTokens(); //creating firebase class object $firebase = new Firebase(); //sending push notification and displaying result echo $firebase->send($devicetoken, $mPushNotification); }else{ $response['error']=true; $response['message']='Parameters missing'; } }else{ $response['error']=true; $response['message']='Invalid request'; } echo json_encode($response); |
- Thats it for the server side coding. Now lets move in Android Studio again to finish our app.
Making Send Notification Option in App
- The first thing we will do is create a separate class for storing all the URLs required. So create a class named EndPoints.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package net.simplifiedcoding.firebasecloudmessaging; /** * Created by Belal on 04/11/16. */ public class EndPoints { public static final String URL_REGISTER_DEVICE = "http://192.168.1.102/FcmExample/RegisterDevice.php"; public static final String URL_SEND_SINGLE_PUSH = "http://192.168.1.102/FcmExample/sendSinglePush.php"; public static final String URL_SEND_MULTIPLE_PUSH = "http://192.168.1.102/FcmExample/sendMultiplePush.php"; public static final String URL_FETCH_DEVICES = "http://192.168.1.102/FcmExample/GetRegisteredDevices.php"; } |
- Now we will create a send notification option for our application. So again come inside activity_main.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?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:id="@+id/activity_main" 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="net.simplifiedcoding.firebasecloudmessaging.MainActivity"> <EditText android:layout_above="@+id/buttonRegister" android:hint="Enter email" android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:layout_centerVertical="true" android:text="Register Device" android:id="@+id/buttonRegister" android:layout_width="match_parent" android:layout_height="wrap_content" /> <!-- this button is added --> <Button android:text="Send Notification" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/buttonRegister" android:layout_centerHorizontal="true" android:id="@+id/buttonSendNotification" /> </RelativeLayout> |
- We added one more button and this button will take us to another activity from where we can send push notification to devices.
Creating Activity For Sending Push Notification
- Now create another EmptyActivity named ActivitySendPushNotification.
- For this activity we will create the following layout.
- We have a Radio Button group for individual or multiple push option. Then a Spinner to display registered devices. Three EditTexts for title, message and image url.
- For the above layout here is the xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_send_push_notification" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" 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="net.simplifiedcoding.firebasecloudmessaging.ActivitySendPushNotification"> <RadioGroup android:id="@+id/radioGroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <RadioButton android:id="@+id/radioButtonSendAll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send to All" /> <RadioButton android:id="@+id/radioButtonSendOne" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send to One" /> </RadioGroup> <Spinner android:id="@+id/spinnerDevices" android:layout_width="match_parent" android:layout_height="wrap_content"></Spinner> <EditText android:id="@+id/editTextTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Message Title" /> <EditText android:id="@+id/editTextMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Message" /> <EditText android:id="@+id/editTextImageUrl" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Image URL (Optional) " /> <Button android:id="@+id/buttonSendPush" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Send Push" /> </LinearLayout> |
- Now the first thing we will do is we will modify the MainActivity.java to open this activity on button click.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
package net.simplifiedcoding.firebasecloudmessaging; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; 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 org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //defining views private Button buttonSendPush; private Button buttonRegister; private EditText editTextEmail; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting views from xml editTextEmail = (EditText) findViewById(R.id.editTextEmail); buttonRegister = (Button) findViewById(R.id.buttonRegister); buttonSendPush = (Button) findViewById(R.id.buttonSendNotification); //adding listener to view buttonRegister.setOnClickListener(this); buttonSendPush.setOnClickListener(this); } //storing token to mysql server private void sendTokenToServer() { progressDialog = new ProgressDialog(this); progressDialog.setMessage("Registering Device..."); progressDialog.show(); final String token = SharedPrefManager.getInstance(this).getDeviceToken(); final String email = editTextEmail.getText().toString(); if (token == null) { progressDialog.dismiss(); Toast.makeText(this, "Token not generated", Toast.LENGTH_LONG).show(); return; } StringRequest stringRequest = new StringRequest(Request.Method.POST, EndPoints.URL_REGISTER_DEVICE, new Response.Listener<String>() { @Override public void onResponse(String response) { progressDialog.dismiss(); try { JSONObject obj = new JSONObject(response); Toast.makeText(MainActivity.this, obj.getString("message"), Toast.LENGTH_LONG).show(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("email", email); params.put("token", token); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } @Override public void onClick(View view) { if (view == buttonRegister) { sendTokenToServer(); } //starting send notification activity if(view == buttonSendPush){ startActivity(new Intent(this, ActivitySendPushNotification.class)); } } } |
Creating a Volley Singleton Class
- As we need to perform http request several time that is why, we are defining a singleton pattern for volley to handle network requests.
- Create a class named MyVolley.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package net.simplifiedcoding.firebasecloudmessaging; import android.content.Context; import android.graphics.Bitmap; import android.support.v4.util.LruCache; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.Volley; /** * Created by Belal on 13/10/16. */ public class MyVolley { private static MyVolley mInstance; private RequestQueue mRequestQueue; private static Context mCtx; private MyVolley(Context context) { mCtx = context; mRequestQueue = getRequestQueue(); } public static synchronized MyVolley getInstance(Context context) { if (mInstance == null) { mInstance = new MyVolley(context); } return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { // getApplicationContext() is key, it keeps you from leaking the // Activity or BroadcastReceiver if someone passes one in. mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); } return mRequestQueue; } public <T> void addToRequestQueue(Request<T> req) { getRequestQueue().add(req); } } |
- Now we will code the ActivitySendPushNotification.java, so come inside the class.
- First define the views and all the required methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
package net.simplifiedcoding.firebasecloudmessaging; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.RadioGroup; import android.widget.Spinner; public class ActivitySendPushNotification extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener { private Button buttonSendPush; private RadioGroup radioGroup; private Spinner spinner; private ProgressDialog progressDialog; private EditText editTextTitle, editTextMessage, editTextImage; private boolean isSendAllChecked; private List<String> devices; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send_push_notification); radioGroup = (RadioGroup) findViewById(R.id.radioGroup); spinner = (Spinner) findViewById(R.id.spinnerDevices); buttonSendPush = (Button) findViewById(R.id.buttonSendPush); editTextTitle = (EditText) findViewById(R.id.editTextTitle); editTextMessage = (EditText) findViewById(R.id.editTextMessage); editTextImage = (EditText) findViewById(R.id.editTextImageUrl); devices = new ArrayList<>(); radioGroup.setOnCheckedChangeListener(this); buttonSendPush.setOnClickListener(this); loadRegisteredDevices(); } //method to load all the devices from database private void loadRegisteredDevices() { } //this method will send the push //from here we will call sendMultiple() or sendSingle() push method //depending on the selection private void sendPush(){ } private void sendMultiplePush(){ } private void sendSinglePush(){ } @Override public void onCheckedChanged(RadioGroup radioGroup, int i) { switch (radioGroup.getCheckedRadioButtonId()) { case R.id.radioButtonSendAll: isSendAllChecked = true; spinner.setEnabled(false); break; case R.id.radioButtonSendOne: isSendAllChecked = false; spinner.setEnabled(true); break; } } @Override public void onClick(View view) { //calling the method send push on button click sendPush(); } } |
- Now we have to load the registered devices to the spinner. We already have the webservice to fetch devices.
Fetching All Devices
- Write the following codes in the method loadRegisteredDevices()Â
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
private void loadRegisteredDevices() { progressDialog = new ProgressDialog(this); progressDialog.setMessage("Fetching Devices..."); progressDialog.show(); StringRequest stringRequest = new StringRequest(Request.Method.GET, EndPoints.URL_FETCH_DEVICES, new Response.Listener<String>() { @Override public void onResponse(String response) { progressDialog.dismiss(); JSONObject obj = null; try { obj = new JSONObject(response); if (!obj.getBoolean("error")) { JSONArray jsonDevices = obj.getJSONArray("devices"); for (int i = 0; i < jsonDevices.length(); i++) { JSONObject d = jsonDevices.getJSONObject(i); devices.add(d.getString("email")); } ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>( ActivitySendPushNotification.this, android.R.layout.simple_spinner_dropdown_item, devices); spinner.setAdapter(arrayAdapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { }; MyVolley.getInstance(this).addToRequestQueue(stringRequest); } |
- If you will run the application now you will see the emails in the spinner.
Sending Push Notification
- Now the last part of this Firebase Cloud Messaging Tutorial and the main thing, sending push notification to the devices.
- So now we will code the remaining methods.
- First inside the method sendPush() write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 |
//this method will send the push //from here we will call sendMultiple() or sendSingle() push method //depending on the selection private void sendPush() { if(isSendAllChecked){ sendMultiplePush(); }else{ sendSinglePush(); } } |
Sending to A Single Device
- Write the following code in method sendSinglePush() for sending to a single device that is selected from the spinner.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
private void sendSinglePush() { final String title = editTextTitle.getText().toString(); final String message = editTextMessage.getText().toString(); final String image = editTextImage.getText().toString(); final String email = spinner.getSelectedItem().toString(); progressDialog.setMessage("Sending Push"); progressDialog.show(); StringRequest stringRequest = new StringRequest(Request.Method.POST, EndPoints.URL_SEND_SINGLE_PUSH, new Response.Listener<String>() { @Override public void onResponse(String response) { progressDialog.dismiss(); Toast.makeText(ActivitySendPushNotification.this, response, Toast.LENGTH_LONG).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("title", title); params.put("message", message); if (!TextUtils.isEmpty(image)) params.put("image", image); params.put("email", email); return params; } }; MyVolley.getInstance(this).addToRequestQueue(stringRequest); } |
- Now you can test the application for single push as well.
- Now lest code the last method of this Firebase Cloud Messaging Tutorial which is about sending multiple push notification.
Sending to Multiple Device
- Write the following code for sendMultiplePush().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
private void sendMultiplePush() { final String title = editTextTitle.getText().toString(); final String message = editTextMessage.getText().toString(); final String image = editTextImage.getText().toString(); progressDialog.setMessage("Sending Push"); progressDialog.show(); StringRequest stringRequest = new StringRequest(Request.Method.POST, EndPoints.URL_SEND_MULTIPLE_PUSH, new Response.Listener<String>() { @Override public void onResponse(String response) { progressDialog.dismiss(); Toast.makeText(ActivitySendPushNotification.this, response, Toast.LENGTH_LONG).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("title", title); params.put("message", message); if (!TextUtils.isEmpty(image)) params.put("image", image); return params; } }; MyVolley.getInstance(this).addToRequestQueue(stringRequest); } |
- Now thats it. You just need multiple emulators now to test the application.
- Bingo! Notifications are working absolutely fine.
- Now if you want the source code of the application you can get it from below.
Firebase Cloud Messaging Source Code
Android Side Source Code
[sociallocker id=1372] Firebase Cloud Messaging Source Code [/sociallocker]
Server Side PHP Code
[sociallocker id=1372] [download id=”3821″]Â [/sociallocker]
So it is the end of Firebase Cloud Messaging Tutorial. This is the longest tutorial so far, and if you want to make this Firebase Cloud Messaging Tutorial work, have patience and follow the whole tutorial carefully.And yes if you have some confusions regarding this Firebase Cloud Messaging Tutorial. Lets meet in comment section. Also share this tutorial among your friends. Thank You 🙂