Android push notification using firebase cloud messaging FCM and Php

FCM(Firebase Cloud Messaging) is a service that helps developers send data from servers  to their Android applications.Using FCM you can send data to your application whenever new data is available instead of making requests to server in timely fashion.Let us see an example of sending push notification messages to multiple android devices.

This example consist of Android and php(php code are using to send fcm messages from server) .First step is to create configure a project in Firebase console.

Contents

  • Create new project in android studio
  • Configure project in firebase developers console
  • Configure gradle with dependencies.
  • Implement android codes.
  • Implementing php code for saving fcm key and sending push notification

Create new project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

Configure Project in Firebase Developers Console.

In this step you need to configure a firebase application . Please refer this tutorial(How to configure firebase project in a console) which will help you to create new project in firebase. If you already have a firebase project for your application skip this step.

Configure gradle with dependencies

Before doing step you need to make sure that the google-services.json file is added to your application which is a part of configuring firebase. The downloaded file should be placed under app folder of your application. After adding that you need to compile the latest version of firebase messaging in your apps build.gradle file

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

and add the following line to the end of the same file.

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

Now add the following dependency to your project level build.gradle file.

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

Now you can sync the gradle

Implement android codes

In this step you need to create certain files with some small set of code.First step is to create a file under java/your package/QuickstartPreferences.java . This is a class which contains just static boolean variables which will be using in application to check wheather you are already registered with FCM.

QuickstartPreferences.java

public class QuickstartPreferences {
    public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer";
}

Next step is to create a service class which will Generate FCM token. Create a class under java/your package/MyFirebaseInstanceIDService.java. In this class the FCM token will get created and you can save the token to your database.For that you need to call a webservice. Here is the code for MyFirebaseInstanceIDService.java

MyFirebaseInstanceIDService.java

package com.codesfor.firebasepushnotification;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";
    private String fcmid;

    @Override
    public void onCreate() {
        super.onCreate();

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        if(refreshedToken !=null){

               sendRegistrationToServer(refreshedToken);

        }
    }

    @Override
    public void onTokenRefresh() {

        //Getting registration token
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

          sendRegistrationToServer(refreshedToken);
    }


    private void sendRegistrationToServer(String token) {

        fcmid = token;
        // Add custom implementation, as needed.
        try {
            if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
               new SendGcmToken().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "http://your domain/create_user.php");
            }
            else {
               new SendGcmToken().execute("http://your domain/create_user.php");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private class SendGcmToken extends AsyncTask<String, Void, Void> {

        // Required initialization

        private String Content;
        private String Error = null;
        String data ="";
        boolean isOkay = true;


        protected void onPreExecute() {

            try{

                data +="&" + URLEncoder.encode("email", "UTF-8")+"="+ "users_email"+"&"
                        + URLEncoder.encode("fcmid", "UTF-8")+"="+fcmid;

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }

        protected Void doInBackground(String... urls) {
            BufferedReader reader=null;

                try
                {
                    URL url = new URL(urls[0]);
                    URLConnection conn = url.openConnection();
                    conn.setDoOutput(true);
                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                    wr.write( data );
                    wr.flush();
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while((line = reader.readLine()) != null)
                    {
                        sb.append(line);
                    }

                    Content = sb.toString();
                }
                catch(Exception ex)
                {
                    Error = ex.getMessage();
                }
                finally
                {
                    try
                    {
                        reader.close();
                    }

                    catch(Exception ex) {}
                }

            return null;
        }

        protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.

            if(!isOkay) {

                Toast.makeText(getApplicationContext(), "Please check internet connection", Toast.LENGTH_SHORT).show();
                MainActivity.setPreference(getApplicationContext(), false, QuickstartPreferences.SENT_TOKEN_TO_SERVER);

            } else {
                try {

                    if(Content != null){
                        JSONObject jsonResponse = new JSONObject(Content);
                        String status = jsonResponse.getString("status");


                        if("200".equals(status)){

                            MainActivity.setPreference(getApplicationContext(), true, QuickstartPreferences.SENT_TOKEN_TO_SERVER);
                        }
                        else{

                            MainActivity.setPreference(getApplicationContext(), true, QuickstartPreferences.SENT_TOKEN_TO_SERVER);

                        }
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }

    }
}

Now modify your MainActivity.java with the below code. This set of code will ensure that the fcm token is already configured and saved in remote server or not. If not it will take you to that service for saving fcm token in the remote server.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    public static String PREFS_NAME = "pref";
    static SharedPreferences settings;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //checking wethr updated token is already sent to server
        if(!getPreference(getApplicationContext(),QuickstartPreferences.SENT_TOKEN_TO_SERVER)){

            //getting refresh token and sending to server
            Intent intent = new Intent(this, MyFirebaseInstanceIDService.class);
            startService(intent);

        }

    }
    //preference for boolean values
    static public boolean setPreference(Context c,boolean value, String key) {
        settings = c.getSharedPreferences(PREFS_NAME, 0);
        settings = c.getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(key, value);
        return editor.commit();
    }

    static public boolean getPreference(Context c, String key) {
        settings = c.getSharedPreferences(PREFS_NAME, 0);
        settings = c.getSharedPreferences(PREFS_NAME, 0);
        boolean result = settings.getBoolean(key, false);
        return result;
    }
}

Next step is create a broadcast receiver class to Handle the incoming notification message,create a class under java/your package/MyFirebaseMessagingService.java

MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        sendNotification(remoteMessage);

    }

    private void sendNotification(RemoteMessage data) {
        Random random = new Random();
        int m = random.nextInt(9999 - 1000) + 1000;
        Intent intent = null;
        intent = new Intent(this, MainActivity.class);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(data.getData().get("Title"))
                .setContentText(data.getData().get("Action"))
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(m/* ID of notification */, notificationBuilder.build());
    }
}

Now You need to have certain permission and you need to register some service in your AndroidManifest . Here is code for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.codesfor.firebasepushnotification">
    <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">

        <!-- fcm -->
        <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <!-- fcm ends -->
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Now we are done with android codes for Fcm. Now you need to create the below two php files and place in your server.

Implementing php code for saving fcm key and sending push notification

create_user.php
This is the api file used for inserting user information into database.

<?php 
$email=$_POST["email"];
$gcmid=$_POST["fcmid"];
include("connection.php");
$sql = "INSERT INTO user(email,fcmid) VALUES ('$email','$fcmid')";
 $result = mysql_query($sql, $con);
 if(mysql_affected_rows()>0){
 
 $final_arr=array();
 $final_arr["status"] = "200";
 $final_arr["msg"] = "successful";
 print_r(json_encode($final_arr));
 }else{
 $final_arr=array();
 $final_arr["status"] = "401";
 $final_arr["msg"] = "successful";
 print_r(json_encode($final_arr));
 }
?>

test_fcm.php

This is the file which is using for sending push notification. You need to use your own api key in the following code to work

<?php
include("connection.php");
$apiKey='place your api key here';
$ids = array();
$sql = "select * from user";
$result = mysql_query($sql);
 
while ($row_topic = mysql_fetch_array($result)) {
$ids [] = $row_topic['fcmid'];
}
 $message_arr=array();
 $message_arr["Action"]= "This is a push notification";
 $message_arr["Title"]="FCM push notification";

 $url = 'https://fcm.googleapis.com/fcm/send';

 $fields = array(
 'registration_ids' => $ids,
 'data' => $message_arr,
 );
 $headers = array(
 'Authorization: key=' . $apiKey,
 'Content-Type: application/json'
 );

 // Open connection
 $ch = curl_init();
 // Set the URL, number of POST vars, POST data
 curl_setopt( $ch, CURLOPT_URL, $url);
 curl_setopt( $ch, CURLOPT_POST, true);
 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
 //curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));

 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 // curl_setopt($ch, CURLOPT_POST, true);
 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));

 // Execute post
 $result = curl_exec($ch);

 // Close connection
 curl_close($ch);
 echo $result;

?>

You need have a file “connection.php” which will be connecting to a Mysql database with a table “user” and fields id,email,fcmid. You need to replace the server key in the above code with your own server key. You can find your applications server key on your firebase console. For more information about finding server key you can refer How to configure firebase application tutorial -section (How to find server key)

Now Run the android project . After installation execute the test_fcm.php file from your browser. It will send notification to all the user registered in your application.

 

 

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *