FCM (Firebase Cloud Messaging) Push Notification to Android Device using PHP API

FCM( Firebase Cloud messaging) is used to send notification to android device. FCM also provide storage for user data, token service, analysis user pattern and many more. FCM is free for limited use. This blog demonstrate how to configure FCM with android app and PHP API. It is very easy and simple to intergrate push notification using FCM( Firebase Cloud messaging). In this blog we will build a user registration android app to our PHP Server and at same time FCM( Firebase Cloud messaging) configuration done in background. After successful login a push notification send to user device contains welcome message via firebase api. Your can also send notification using Firebase console. Below is detail of step follow in this tutorial.



1) Create Firebase login and get json file from google.
2) Configure FCM in android studio Gradle file.
3) Firebase Message type.
4) Setup android project to receive notification.
5) Run App in Real Device using USB Debugging.

Android Device get push notification from PHP Server Using Firebase cloud messaging(FCM)

Login & Download source code

download-code350-100

50 days android course

 

http://go.oclasrv.com/afu.php?zoneid=1496570

1. Create Firebase login and get JSON file

Before start firebase first create new project in android studio.Because android project package name will be needed in Firebase.
1. Now you need to do is go to https://firebase.google.com/ and make an account to gain access to their console. After that you can start by creating your first project.

2. Give the package name of your project (i used blueappsoftware.firenotification ) to get configure JSON file from Firebase. then download the google-services.json file and place this file inside “app” folder of your android studio project that you are going to create in next step.

3. Create a new project in Android Studio from File ⇒ New Project. While filling the project details, use the same package name which you gave in firebase console. Like my android project name is blueappsoftware.firenotification . Place the downloaded file google-services.json inside “app” folder of android studio project.

2. Configure FCM in android studio Gradle file

1. Open build.gradle(Module:app) file in android studio. Add this line at the end of file.

// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

2. Now open project gradle file build.gradle(Project) in android studio. Add this line in dependency

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        // add this line FCM configuration
        classpath 'com.google.gms:google-services:3.0.0'
    }
}



Firebase Message Type

Firebase Cloud Messaging have two type of messaging services. 1) Notification Message 2) Data Message
Firebase Document says”Use notification messages when you want FCM to handle displaying a notification on your client app’s behalf. Use data messages when you want to process the messages on your client app.
The app server can send a message including both notification and data payloads. In such cases, FCM handles displaying the notification payload, and the client app handles the data payload”.

Notification message

{
    "to": "4IdGZEowjTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBAUAA4IBAQ...",
    "notification": {
        "body": "first notification received in android app from FCM!",
        "title": "first notification received",
    }
}

Data message

{
   "to" : "4IdGZEowjTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBAUAA4IBAQ...",
   "data" : {
     "name" : "first notification received in android app from FCM!",
     "anytitle" : "notification first",
     "other" : "other details"
   }
 }

Setup android project to receive notification

Now to start app development. create two java class file. first one for getting token from FCM server and second java class file for receiving notification from either Firebase console or from our own PHP server.

MyFirebaseInstanceIDService.java

This java file get FCM token from Firebase server when app install on user device. Token automatically update from Firebase server.

package blueappsoftware.firenotification;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

/**
 * Created by jain on 25-Feb-17.
 */

        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.os.AsyncTask;
        import android.os.Handler;
        import android.os.Looper;
        import android.preference.PreferenceManager;
        import android.support.v4.content.LocalBroadcastManager;
        import android.util.Log;
        import android.widget.Toast;

        import com.google.firebase.iid.FirebaseInstanceId;
        import com.google.firebase.iid.FirebaseInstanceIdService;

        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.text.DateFormat;
        import java.text.SimpleDateFormat;
        import java.util.ArrayList;
        import java.util.Calendar;
        import java.util.List;
        import java.util.Random;
        import java.util.Timer;

        import org.apache.http.HttpEntity;
        import org.apache.http.HttpResponse;
        import org.apache.http.NameValuePair;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.entity.UrlEncodedFormEntity;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.message.BasicNameValuePair;
        import org.json.JSONObject;

        import blueappsoftware.firenotification.model.Token;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    SharedPreferences pref;

    private static final String TAG = "MyFirebaseIIDService";
    public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";
    private static String RegistorToken;
    private static final int MAX_ATTEMPTS = 5;
    private static final int BACKOFF_MILLI_SECONDS = 2000;
    private static final Random random = new Random();
// insert function me use

    private DateFormat df = new SimpleDateFormat("h:mm a");

    private Calendar c = Calendar.getInstance();
    //    System.out.println("Current time => " + c.getTime());
    private SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");

    private String time ,date;
    private InputStream is=null;
    private String result=null;
    private String line=null;
    private int code ;
    private int i=0;

    long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);

    Handler handler = new Handler(Looper.getMainLooper());
    @Override
    public void onTokenRefresh() {
        // this line get token
        RegistorToken = FirebaseInstanceId.getInstance().getToken();

          Log.e(TAG, "Refreshed token: " + RegistorToken);
        // store token into shared preference
        final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        // int value=(mSharedPreference.getInt("Install", 1));

        SharedPreferences.Editor editor = mSharedPreference.edit();
        /// if store token locally

        pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        // 0 - for private mode
        final SharedPreferences.Editor editor2 = pref.edit();
        editor2.putString("newtoken",RegistorToken);
        editor2.commit();

        if (mSharedPreference.getInt("tokeninsert",0)!=1) {
            //   Log.e("my firebase id ","insert new token " );
            sendRegistrationToServer(mSharedPreference.getString("update","no") );

        }else {
            //   Log.e("my firebase id ","update old token  ");
            sendRegistrationToServer(mSharedPreference.getString("update","yes") );
        }

    }

    public void sendRegistrationToServer(final String update ) {

        // Once FCM returns a registration id, we need to register on our server
        // As the server might be down, we will retry it a couple time.
       try{
                //  Log.e("serverUtility "," trying attemp to connect server 1/5  "+ i);
                if (i >= MAX_ATTEMPTS) {
                    // Log.e(TAG, "Failed to register on attempt " + i + ":" );
                }else {
                    sendTokenToServer dl = new sendTokenToServer();
                    dl.execute(update);
                    i++;
                }

        }catch (IndexOutOfBoundsException e){
            // Log.e("my firebase id se"," no user data retry "+e);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    /// after 4 minute
                    sendRegistrationToServer(update);

                }
            }, 240000);  //   4 minute
        }

    }


    public static String getRegistorToken(){
        return RegistorToken;
    }

    public class sendTokenToServer extends AsyncTask<String, Void, String> {

        //  final SharedPreferences mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        protected String doInBackground(String[] params) {
            String update = params[0].toString();
            // Log.e("my fire id ","send update id yes/no   --- "+ update);
            // current time
            time = df.format(Calendar.getInstance().getTime());
            date = dt.format(c.getTime());

            // get usrnm and psswrd from db
            RegistorToken= pref.getString("newtoken","none");

             Log.e(" myFirebase ID Service ","  asyncTask send token to server "  + RegistorToken +" time is "+time );
            ArrayList nameValuePairs = new ArrayList();

            nameValuePairs.add(new BasicNameValuePair("time", time) );
            nameValuePairs.add(new BasicNameValuePair("date", date) );
            nameValuePairs.add(new BasicNameValuePair("token",  RegistorToken));
            nameValuePairs.add(new BasicNameValuePair("username",  RegistorToken));
            nameValuePairs.add(new BasicNameValuePair("phone",  RegistorToken));

            try
            {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://app.blueappSoftware.in/insertTokenToServer.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs ,"UTF-8"));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                // Log.d("pass 1", "connection success ");
            }
            catch(Exception e)
            {
                // Log.e("Fail 1", e.toString());
                //  Log.e("my firebase ID service "," sendID to server fail 1    invalid ip");
            }

            try
            {
                BufferedReader reader = new BufferedReader (new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                // Log.d("pass 2", "connection success " + result);
            }
            catch(Exception e)
            {
                // Log.e("Fail 2", e.toString());
                // Log.d(" my firebase ID  "," exception pass 2 ");
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            //   Log.d(" Tripstart pass 3 "," result  " + result);
            try
            {
                JSONObject json_data = new JSONObject(result);
                code=(json_data.getInt("Fcmcode"));
                //     Log.d("pass 3", "connection success " + code);
                if(code==1)
                {
                    pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    // 0 - for private mode
                    final SharedPreferences.Editor editor = pref.edit();
                    editor.putInt("tokeninsert",1);
                    // Log.d("my firebase ID service "," result insert  " + code);
                    editor.putString("update","yes");
                    editor.commit();
                    //  Log.e("my firebase id ser"," update change to yes");

                }else if(code==2){
                    //   Log.e("my firebase ID service "," result update succesful  " + code);
                }
                else
                {
                    try {
                        // Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
                        Thread.sleep(backoff);
                    } catch (InterruptedException e1) {
                        // Activity finished before we complete - exit.
                        // Log.d(TAG, "Thread interrupted: abort remaining retries!");
                        Thread.currentThread().interrupt();
                        return;
                    }
                    sendRegistrationToServer(pref.getString("update","no"));
                    // Log.e("my firebase ID service "," result fail    try again .");
                }
            }
            catch(Exception e)
            {
                // Log.e("Fail 3", e.toString());
                //  Log.e(" my firebase ID service"," fail 3 error - "+ result + ", "+ code +", ");
            }

            Intent nextScreen = new Intent(getApplicationContext(), MainActivity.class);
            nextScreen.putExtra("tokenId", RegistorToken);
            nextScreen.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //Sending data to another Activity
            startActivity(nextScreen);


        }
    }


}

MyFirebaseMessagingService.java

This java file responsible for receiving notification from Firebase console or PHP server. Remember if you are using notification type FCM message and if app is in background(generally it is background) then this java file will not execute onMessageReceived(RemoteMessage remoteMessage) method. So my best advice to you is always use Data type FCM message, so your app will receive notification every time whether app is either in foreground or in background.

package blueappsoftware.firenotification;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.DisplayMetrics;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * Created by jain on 25-Feb-17.
 */


        import android.app.ActivityManager;
        import android.app.Notification;
        import android.app.NotificationManager;
        import android.app.PendingIntent;
        import android.content.ComponentName;
        import android.content.Context;
        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.content.res.Resources;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.media.MediaPlayer;
        import android.media.RingtoneManager;
        import android.net.Uri;
        import android.os.Build;
        import android.preference.PreferenceManager;
        import android.support.v4.app.NotificationCompat;
        import android.util.DisplayMetrics;
        import android.util.Log;

        import com.google.firebase.messaging.FirebaseMessaging;
        import com.google.firebase.messaging.FirebaseMessagingService;
        import com.google.firebase.messaging.RemoteMessage;

        import java.io.IOException;
        import java.io.InputStream;
        import java.net.HttpURLConnection;
        import java.net.URL;
        import java.util.List;


public class MyFirebaseMessagingService extends FirebaseMessagingService  {

    private static final String TAG = "MyFirebaseMsgService";
    public Boolean RefrehserActivity= false;
    SharedPreferences pref;
    Bitmap bitmap = null;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        final SharedPreferences.Editor editor = pref.edit();

        //It is optional to store notification in share preference
        editor.putString("fcmTitle", remoteMessage.getData().get("title"));
        editor.putString("fcmBody",remoteMessage.getData().get("body"));
        editor.putString("fcmid",remoteMessage.getData().get("ïd"));
        editor.commit();

        // display image in notification
        //imageUri will contain URL of the image to be displayed with Notification
        String imageUri = remoteMessage.getData().get("image");
        String subtitle = remoteMessage.getData().get("subtitle");
        //To get a Bitmap image from the URL received
        bitmap = getBitmapfromUrl(imageUri);

        if (bitmap!=null && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN ){
            sendNotificationImage(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"), bitmap , subtitle);
        }else {
            //generate notification with image android version above api 15
            sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
        }

    }

    //This method is only generating push notification
       private void sendNotification( String title, String messageBody) {

        int icon = R.mipmap.logo;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Intent notificationIntent = new Intent();
        PendingIntent intent ;
//         MainActivity mn = new MainActivity();
        final SharedPreferences.Editor editor = pref.edit();

        if (activityforgoundcheck()){
            // Log.e("MyFireMessage"," activity in forground");
            editor.putBoolean("refresh", true);
            editor.commit();

            notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.putExtra("newMessagetitle", title);
            notificationIntent.putExtra("newMessage", messageBody);
            //notificationIntent.putExtra("refreshActivity", true);
            // set intent so it does not start a new activity
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        }else {
            //  Log.e("MyFireMessage"," activity in background");
            notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.putExtra("newMessagetitle", title);
            notificationIntent.putExtra("newMessage", messageBody);
            // set intent so it does not start a new activity
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        }
        Notification noti = null;

        noti = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.logo)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.raw.logo ))
                //  .setStyle(new NotificationCompat.BigPictureStyle()
                //          .bigPicture(image))/*Notification with Image*/  image not display in notification
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                //   .setSound(soundUri) //This sets the sound to play
                .setContentIntent(intent).getNotification();
        MediaPlayer mp= MediaPlayer.create(getApplicationContext() , R.raw.notitone);
        mp.start();

        noti.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, noti);

    }

    public void sendNotificationImage(String title, String messageBody , Bitmap image, String subtitle){
        int icon = R.mipmap.logo;
        long when = System.currentTimeMillis();
        // Log.d("GCMIntentService  "," new message receive "+ messageBody);
        // store all "message" into db and  lblMessage.setText(notificationMSG); me new massage hi set kro.
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //  Notification notification = new Notification(icon, message, when);
        Intent notificationIntent = new Intent();
        PendingIntent intent ;
//         MainActivity mn = new MainActivity();
        final SharedPreferences.Editor editor = pref.edit();
        if (activityforgoundcheck()) {
            //  Log.e("MyFireMessage", " activity in forground");
            editor.putBoolean("refresh", true);
            editor.commit();

            notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.putExtra("newMessagetitle", title);
            notificationIntent.putExtra("newMessage", messageBody);
            //notificationIntent.putExtra("refreshActivity", true);
            // set intent so it does not start a new activity
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        }else {
            notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.putExtra("newMessagetitle", title);
            notificationIntent.putExtra("newMessage", messageBody);
            // set intent so it does not start a new activity
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        }
        Notification noti = null;
        //if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        noti = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.logo)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.raw.logo ))
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(image))/*Notification with Image*/
                .setContentTitle(title)
                .setSubText(subtitle)
                //.setContentText(messageBody)
                .setAutoCancel(true)
                //   .setSound(soundUri) //This sets the sound to play
                .setContentIntent(intent).getNotification();

        MediaPlayer mp= MediaPlayer.create(getApplicationContext() , R.raw.notitone);
        mp.start();

        noti.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, noti);

    }

    public Boolean activityforgoundcheck(){
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        List services = activityManager
                .getRunningTasks(Integer.MAX_VALUE);
        boolean isActivityFound = false;

        if (services.get(0).topActivity.getPackageName().toString()
                .equalsIgnoreCase(getApplicationContext().getPackageName().toString())) {

            isActivityFound = true;
        }
        return  isActivityFound;
    }

    /*
    *To get a Bitmap image from the URL received
    * */
    public Bitmap getBitmapfromUrl(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
            return bitmap;

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

        }
    }
}

gradle file app module

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
    defaultConfig {
        applicationId "blueappsoftware.firenotification"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.4.0'
    testCompile 'junit:junit:4.12'
    //Add this line firebase
    compile 'com.google.firebase:firebase-messaging:9.0.0'

    compile files('libs/google-http-client-1.20.0.jar')
    compile files('libs/httpclient-4.5.1.jar')
}
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

MainActivity.java

MainActivity.java file only containing two textview. first one display token id from firebase console.

package blueappsoftware.firenotification;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView token, notification;
    private String tokenid ="", notificasn="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent i = getIntent();
        tokenid = i.getStringExtra("tokenId");
        notificasn = i.getStringExtra("newMessagetitle");

        token = (TextView) findViewById(R.id.token);
        notification = (TextView) findViewById(R.id.notification);

        token.setText(tokenid);
        notification.setText(notificasn);
    }
}



Server side code

Now we will develop our own server so that each token store in mysql databse and we will send notification form our server without going to Firebase console. first create table in mysql

insertTokenToServer.php

This PHP file received token from android device and store FCM token into mysql database.

<?php
	include('db_connection.php'); 
	
   global $conn ;
try{
mysqli_set_charset($conn, 'utf8');

	$time = htmlentities($_REQUEST['time']);
	$date =htmlentities($_REQUEST['date']);
	$token =htmlentities($_REQUEST['token']);
	$fname =htmlentities($_REQUEST['firstname']);
	$lname =htmlentities($_REQUEST['lastname']);
	$phonenumber =htmlentities($_REQUEST['phonenumber']);
	$update =htmlentities($_REQUEST['update']);
	$userID =htmlentities($_REQUEST['userID']);

	// Change the line below to your timezone!
	//_default_timezone_set("Asia/Kolkata");
  //	$date = date('YYYY-MM-DD h:i:s a', time());
	
	//$time = $date."-".$time;

	// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
	}

/// check token already exit for user nor not
	$sql = 'SELECT firstname,lastname FROM gcm_users WHERE userId=?';
	$stmt = $conn->prepare($sql);

	if($stmt === false) {
  		trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->errno . ' ' . $conn->error, E_USER_ERROR);
	}
	$stmt->bind_param('i', $userID);
	$stmt->execute();
 
	$res = $stmt->get_result();
	while($row = $res->fetch_array(MYSQLI_ASSOC)) {
    		$dbfname = $row['firstname'];
		$dblname = $row['lastname'];
	}	
 	/// check token already exit for user
	if($dbfname === $fname && $dblname === $lname){

If(  	$stmt = $conn->prepare("UPDATE gcm_users SET  gcm_regid =? ,date=?, time=? WHERE userId =? AND firstname=? AND lastname=?") ){

     $stmt->bind_param("sssssi", $token, $date,  $time , $userID,$fname, $lname);

	$stmt->execute();
// response to android device -- update done
	$flag['Fcmcode']=2;
	print(json_encode($flag));
}

   }else{
    /// if user token not exist
if(	$stmt = $conn->prepare("INSERT INTO gcm_users (gcm_regid, userId, firstname, lastname, number, date, time) VALUES (?,?,?,?,?,?,?)") ){

    $stmt->bind_param("sisssss", $token, $userID, $fname, $lname, $phonenumber,$date, $time);

	$stmt->execute();	
 	// response to android device -- insert done
	$flag['Fcmcode']=1;
	print(json_encode($flag));
}

    }

	
   }
catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
?>

Database connection file

<?php
//include('config.php'); //As functions.php is not included

define('HOST','yourhostserver');
define('USER','databaseuser');
define('PASS','databasepassword');
define('DB','databasename');

define("SERVER_KEY", "Firebasekey");
/// get Firebase key - --> GOTO firebase console --> Overview ---> packagename in center of screen click on THREE DOT ----> select setting----> Web API key.

$conn = new mysqli(HOST, USER, PASS, DB);
 
// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}
?>



Send Notification from PHP server

This PHP file display a form to send notification to android device. Fill all the details in this form.
1)Title that display in notification bar in android phone.
2) Subtitle- small text below title line
3) Image that display in notification
4) Extra message for app as body
5) select User token OR select user unique ID from mysql database to whose you want to send notification.
6) To make your form safe use any private key here. Remember First edit this key in FirebaseServerMultiple.php file as you want.

When you want to send notification just open this file in web browser. Fill all details select user unique id from mysql database. OR you can edit this code to select user token only from mysql databse.

<?php
include('FireBaseServerMultiple.php');

if( isset($_POST['submit']) )
{
	if (empty($_POST['title']) ) 
	{
		$error = " type title ";
	}else
	if (empty($_POST['body']) ) 
	{
		$error = " type your massege";
	}else
	if (empty($_POST['id']) ) 
	{
		$error = " type id ";
	}else
	
	if (empty($_POST['image']) ) 
	{
		$error = " ads image full url ";
	}else
	if (empty($_POST['other']) ) 
	{
		$error = " other empty ";
	}else
	{

    //be sure to validate and clean your variables
    $title = htmlentities($_POST['title']);
    $subtitle = htmlentities($_POST['subtitle']);
    $body = htmlentities($_POST['body']);
    $id = htmlentities($_POST['id']);
    	$adsurl  =  htmlentities($_POST['image']);
    $idofuser =  htmlentities($_POST['idofuser']);
    $other = htmlentities($_POST['other']);

    $title = stripslashes($title);
    $subtitle = stripslashes($subtitle);
    $body = stripslashes($body);
    $id = stripslashes($id);
    $adsfull = stripslashes($adsfull);
    $idofuser = stripslashes($idofuser);
    $other = stripslashes($other);

	//then you can use them in a PHP function. 
    $result = sendNotification($title, $body, $id, $adsurl, $subtitle, $other, $idofuser ); 

	}
}

if( isset($result) )
{ 	echo $result; 		//print the result above the form
	
}
?>


<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
    <title>FCM Notification</title>
<style>

* {
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

body {
  font: 16px Helvetica;
  background: #d35400;
}

section {
  width: 70%;
  background: #ecf0f1;
  padding: 0 30px 30px 30px;
  margin: 60px auto;
  text-align: center;
  border-radius: 5px;
}


h1 {
  font-size: 24px;
  font-weight: 100;
  margin-bottom: 30px;
}

input {
  width: 100%;
  background: #ffffff;
  border: none;
  height: 30px;
  margin-bottom: 15px;
  border-radius: 5px;
  text-align: center;
  font-size: 14px;
  color: #7f8c8d;
}

input:focus {
  outline: none;
}

button {
  width: 100%;
  height: 30px;
  border: none;
  background: #3498db;
  color: #ecf0f1;
  font-weight: 100;
  margin-bottom: 15px;
  border-radius: 5px;
  transition: all ease-in-out .2s;
  border-bottom: 3px solid #2980b9;
}

button:focus {
  outline: none;
}

button:hover {
  background: #2980b9;
}

h2 {
  font-size: .75em;
}

a {
  color: #e74c3c;
  text-decoration: none;
  transition: all ease-in-out .2s;
}

a:hover {
  color: #c0392b;
}


</style>
    
    
  </head>

  <body>

    <section>
  <br><br>	<br><br><hr>
  <h1>Notification Form</h1>

  <form action=""  method="post">
    <input id='title' name='title' placeholder='title' type='text' autocomplete="off">
	
    <input id='subtitle' name='subtitle' placeholder='Subtitle' type='text' autocomplete="off">
    
    <input id='body' name='body' placeholder='body' type='text' autocomplete="off">
	
    <input id='id' name='id' placeholder='id' type='text' autocomplete="off">
	
    <input id='image' name='image' placeholder='image web url ' type='text'>

	<input id='idofuser' name='idofuser' placeholder='select which user' type='text' 
autocomplete="off">

	<input id='other' name='other' placeholder='your private key' type='password' autocomplete="off">

	<input name="submit" type="submit" value="submit">
		<br><br>	<br><br>
	 <label ><?php echo $error; ?> </label >

  </form>
  
   </section>  
    
  </body>
</html>

FirebaseServerMultiple.php

<?php
include('db_connection.php'); 

function sendNotification($title, $body, $id, $adsurl, $subtitle, $other, $usernameid ){
	global $conn ;
	try{
		// verify admin
		if($other === "yourprivatekey" ){
			// Check connection
			if ($conn->connect_error) {
				die("Connection failed: " . $conn->connect_error);
			}
			/// get user id 
			if(!empty($usernameid) ){
				$sql2 = 'SELECT gcm_regid, userId FROM FCMtoken WHERE userId='.$usernameid ;
			}
			$stmt2 = $conn->prepare($sql2);
			if($stmt2 === false) {
				trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->errno . ' ' . $conn->error, E_USER_ERROR);
			}
			$stmt2->execute();
			// this array store static of notification send
			$token = array();
			$userid = array();
			$staticSend = array();
			$staticFail = array();
			$failedcount =0;
			$sucesscount =0;
			/* Fetch result to array */
			$res2 = $stmt2->get_result();
			while($row2 = $res2->fetch_array(MYSQLI_ASSOC)) {
				$token[] = $row2['gcm_regid'];
				$userid[] = $row2['userId'];
			}	
			//echo " ----userid ---- ".$userid[0] ;
			$path_to_firebase_cm = 'https://fcm.googleapis.com/fcm/send';
			$fields = array(
				'data' => array('title' => $title, 'body' => $body, 'id' => $id, 'image' => $adsurl, 'subtitle' => $subtitle ),
				'registration_ids' => $token,
				'priority' => "high"
			);
			$headers = array(
				'Authorization:key=' . SERVER_KEY,
				'Content-Type:application/json'
			);		
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $path_to_firebase_cm); 
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); 
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
			$result = curl_exec($ch);
			if ($result === FALSE) {
       				die('Curl failed: ' . curl_error($ch));
   			}
			curl_close($ch);
			$myArray = json_decode($result, true);
			
                 $failedcount = $myArray['failure'] ; 
                $sucesscount = $myArray['success'] ;
			echo "successful -----".$myArray['success']. "------failed -----".$myArray['failure']."--- results---".$result;
			//echo "this is result ".$result;
			/*
///// here store FCM response into your server database- so if some notification failed then you can resend to user.
			if($myArray['success']== "1")
			{		$deliver = "yes";
			 $staticSend[$sucesscount] = 	array(	'userid' =>$userid,
												  'status' =>$result   );
			 $sucesscount++;
			}else{    
				$deliver="no";
				$staticFail[$failedcount] = 	array(	'userid' =>$userid,
													  'status' =>$result   );	
				$failedcount++;
			}
			echo "\n<br /> Send to ".$userid."   deliver successfull ".$deliver;
			$deliveryReport = json_encode($staticSend);
			$failedReport  = json_encode($staticFail);
			date_default_timezone_set('Asia/Kolkata');
			*/
			$todaydate =date("Y-m-d");
			$todaytime =date("h:i:sa");

			//echo "insert id-".$id."-title-".$title."-dev re-".$deliveryReport."-failrep-"
			//.$failedReport."-secu no-".$sucesscount."-fail no-".$failedcount;
			
// insert static to database
			if($stmt3 = $conn->prepare("INSERT INTO notificationstatics (notiId, title, time, date, deliver, failed, deliverNo, failedNo) VALUES (?,?,?,?,?,?,?,?)") ){
				$stmt3->bind_param("isssssii", $id, $title, $todaytime, $todaydate, $result , $result , $sucesscount, $failedcount);
				$stmt3->execute();
				//echo "\n<br /> insert static into server";
			}else{
				//echo "\n<br /> insert static into server failed";
			}
		}// other close
	}
	catch(PDOException $e)
	{
		echo "Error: " . $e->getMessage();
	}
}
?>

Run App in Real Device using USB Debugging

Login & Download source code

download-code350-100




Posted in andorid and tagged , , .

I Am Post Graduation (M.Tech. C.S.E) from VNIT, Nagpur. I Have Published Two Research Paper On International Journal. My Apps on Google Play Store- Sanyukt Parivar(Mp Police ), NOTOtag- Digital Chhindwara, The Tubby-VoiceRecognizer & More.
Contact me at kamal.bunkar@blueappsoftware.in

33 Comments

  1. I love your blog.. very nice colors & theme. Did you create this
    website yourself or did you hire someone to do it for you?
    Plz respond as I’m looking to create my own blog and would like to find
    out where u got this from. appreciate it

  2. Pretty great post. I just stumbled upon your weblog and wanted to say
    that I’ve truly loved browsing your blog posts.
    In any case I’ll be subscribing for your feed and I hope you write once more very soon!

  3. Hi there! This post could not be written any better!
    Reading through this post reminds me of my good old room mate!
    He always kept talking about this. I will forward this article to him.
    Fairly certain he will have a good read. Thank you for sharing!

  4. Hi there! Quick question that’s totally off topic.
    Do you know how to make your site mobile friendly?
    My weblog looks weird when browsing from my iphone4.
    I’m trying to find a template or plugin that might
    be able to fix this issue. If you have any recommendations, please share.
    Thank you!

  5. This is really attention-grabbing, You are an overly skilled blogger.
    I have joined your feed and look forward to in the hunt
    for extra of your great post. Also, I have shared your site in my social networks

  6. I’m really enjoying the theme/design of your blog.

    Do you ever run into any browser compatibility issues?

    A few of my blog audience have complained about my site not
    working correctly in Explorer but looks great in Chrome.
    Do you have any solutions to help fix this issue?

  7. I was recommended this web site by my cousin. I’m
    not sure whether this post is written by him as no one else
    know such detailed about my problem. You are wonderful!

    Thanks!

  8. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy reading your
    blog and I look forward to your new updates.

  9. Having read this I thought it was very informative. I appreciate you finding the time and
    energy to put this short article together. I once again find myself personally spending a lot of time both reading and posting comments.
    But so what, it was still worthwhile!

  10. hi! may i know is your code complete? because i run the program and does nothing, i have download the given source code.

    • Yes this code is working…You have to create file on php server to store FCM key into your database for future use. First check on your android studio log whether FCM token is printing OR not. If it is printing in log than send token to your web server.

  11. Good day! I could have sworn I’ve been to
    this website before but after going through
    a few of the articles I realized it’s new to me.

    Nonetheless, I’m certainly delighted I found it and I’ll be book-marking it and checking back regularly!

  12. Spot on with this write-up, I absolutely feel this website needs much more attention. I’ll probably be returning to read
    through more, thanks for the info!

  13. Hey very cool website!! Man .. Excellent ..
    Amazing .. I will bookmark your site and take the feeds additionally?
    I am glad to search out numerous useful info here
    in the submit, we need work out more strategies
    on this regard, thanks for sharing. . . . . .

  14. Pingback: ExoPlayer Android Example- Best Alternative of VideoView By Kamal

  15. Pingback: Simplest way to get WordPress Post in Android App- REST API

  16. I just like the helpful information you supply to your articles.

    I’ll bookmark your blog and test once more here frequently.
    I’m fairly sure I will learn many new stuff proper here!
    Good luck for the following!

Comments are closed.