Hey Technoz! hope you are doing good. In this tutorial, we will see how to send push notification in android using php mysql. We all know, the notification is a thing which is displayed outside the UI of our app. We are using a Firebase Cloud Messaging (FCM) service to send a notification to user. If you don’t know what is firebase, then read the short introduction below. Otherwise, you can skip that part.
Firebase Cloud Messaging (FCM):
The FCM is a service owned by Google. Indeed, previously it was named Google Cloud Messaging. However, Firebase is its advanced version. It provides many services like cloud messaging, real time database, Hosting etc. For this tutorial, we will be using the cloud messaging to send notifications to android device. To know more, go to official Firebase website.
This tutorial is a combination of two things. One is registration, login of user using REST api and another is to display the notification to intended user. So, u might feel this tutorial a bit lengthy. Therefore, I have divided this tutorial into two modules, for better understanding and neatness.
1. Android Module
Firstly, Lets move towards the android app module to send push notification in android using PHP MySQL.
Building Notification
For building project to send Push Notification in Android using php mysql, Open android Studio and start a new project or use an existing project with which, you want to enable Firebase notifications. Start with a new empty activity. We will need to first make the app able to show notifications. Thus, create a new class NotificationHelper.java
and paste the following code in it.
package net.softglobe.fcmphpmysql; import android.content.Context; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; public class NotificationHelper { public static void displayNotification(Context context, String title, String text){ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, MainActivity.CHANNEL_ID) .setContentTitle(title) .setContentText(text) .setSmallIcon(R.drawable.user); NotificationManagerCompat notificationCompat = NotificationManagerCompat.from(context); notificationCompat.notify(1,mBuilder.build()); } }
The above code contains the static method to show the notification. We can call this method anywhere to display the notification. The method displayNotification()
is taking three arguments. First is context, which gives the context of the application, second is the title of the notification and third is the body of the notification. We are using a png icon for notification.
Adding Firebase to Project
We are building the system which can send the push notification in android to intended device. Firstly, we have to add Firebase in our project. It is much simple. Go to project’s menu Tools->Firebase. A vertical panel will be opened on the right side which has lot of options available for integration in the project. Click on Cloud Messaging and set up FCM. Click on connect to Firebase button. It will launch a browser in background through which u have to sign up with your Google account. So, you will be signed in to android studio.
Secondly, click on ‘Set up cloud messaging’ button. then click on ‘Accept Changes’ and the required dependencies will be added in your project. Wait for the project to build successfully and you are done! Firebase is added in your project. You will see green ticks in the right panel as shown in image below.
Generating token
Thus, every device is registered with Firebase with a unique registration token. As soon as the we will initialize the app, it generates the token. we can use it to send notifications to that device only. we will first generate the token and display it to make sure that we have set up firebase successfully and we are getting a token. So, lets go to activity_main.xml
and put the following code in it.
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/tokentxt" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Token will be displayed here" android:textSize="20sp"/> </LinearLayout> </ScrollView>
The above code has a TextView which will show the generated token.
Now for background things, come to the MainActivity.java
and put the following code in it.
package net.softglobe.fcmphpmysql; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.NotificationChannel; import android.app.NotificationManager; import android.os.Build; import android.os.Bundle; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; public class MainActivity extends AppCompatActivity { static final String CHANNEL_ID = "technopoints_id"; static final String CHANNEL_NAME = "technopoints name"; static final String CHANNEL_DESC = "technopoints desc"; TextView tokentxt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tokentxt = findViewById(R.id.tokentxt); FirebaseInstanceId.getInstance().getInstanceId() .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { @Override public void onComplete(@NonNull Task<InstanceIdResult> task) { if (task.isSuccessful()){ String token = task.getResult().getToken(); tokentxt.setText("Token: "+token); } else { tokentxt.setText("Token Not Generated"); } } }); //Creating notification channel for devices on and above Android O if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); channel.setDescription(CHANNEL_DESC); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } } }
In the onCreate()
method above, we have getting the instance of firebase. Through it, we are calling the OnCompleteListener()
method which gives the result in form of task
variable. We can call isSuccessful()
method to know if the task is successful or not. If succeed, this method returns true, else returns false. Finally on task success, We are getting the token by applying getResult()
and getToken()
methods on task variable. and setting the token on the TextView
.
The code below it is related with notification. In android, the versions O and above are required to create a notification channel before showing the actual notification. Thus, we are checking the android version of device OS and creating the notification channel accordingly. Try running the app now. You will see the token in the TextView
as shown in image below.
The above screen displays the generated token. however, I can’t show the full token for security reasons 🙂 But you will get an idea how it will be shown. As the string is generated, we got a confirmation that the firebase is set up correctly. The token plays an essential role in sending push notification in android using php mysql.
Building Login/Registration Mechanism
Adding necessary code
Now, what we will create a simple user login and registration mechanism. Thus we will pick any one of registered user and send notification to it from the web page. For that, we have to create a login activity, So, lets update the code in activity_main.xml
layout as follows.
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="FCM Tutorial" android:textSize="25sp" android:gravity="center_horizontal" android:textStyle="bold" android:layout_marginBottom="20sp"/> <EditText android:id="@+id/tv_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter email"/> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter password" android:inputType="textPassword"/> <Button android:id="@+id/submitbtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login / Sign up" /> <ProgressBar android:id="@+id/progress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:visibility="gone"/> </LinearLayout> </ScrollView>
That all about designing. Now, lets build the back end tasks. Thus, open MainActivity.java
and paste the following code in it.
package net.softglobe.fcmphpmysql; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; 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.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; public class MainActivity extends AppCompatActivity { static final String CHANNEL_ID = "technopoints_id"; static final String CHANNEL_NAME = "technopoints name"; static final String CHANNEL_DESC = "technopoints desc"; static String SHARED_PREF_NAME = "net.softglobe.fcmphpmysql"; EditText emailtxt,passwordtxt; ProgressBar progressBar; String token,email,password; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); emailtxt = findViewById(R.id.tv_email); passwordtxt = findViewById(R.id.password); progressBar = findViewById(R.id.progress); //Generating Token FirebaseInstanceId.getInstance().getInstanceId() .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { @Override public void onComplete(@NonNull Task<InstanceIdResult> task) { if (task.isSuccessful()){ token = task.getResult().getToken(); } else { Toast.makeText(MainActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show(); } } }); button = findViewById(R.id.submitbtn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { email = emailtxt.getText().toString(); password = passwordtxt.getText().toString(); if (TextUtils.isEmpty(email)){ Toast.makeText(MainActivity.this, "Enter Email", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(password)){ Toast.makeText(MainActivity.this, "Enter Password", Toast.LENGTH_SHORT).show(); } else { LoginRegister(token,email,password); } } }); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); channel.setDescription(CHANNEL_DESC); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } } @Override protected void onStart() { super.onStart(); SharedPreferences preferences = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE); boolean isLoggedIn = preferences.getBoolean("loggedIn",false); if (isLoggedIn){ Intent intent = new Intent(this, ProfileActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } } private void LoginRegister(final String token, final String email, final String password) { class Login extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); progressBar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); progressBar.setVisibility(View.GONE); try { //converting response to json object JSONObject obj = new JSONObject(s); //if no error in response if (obj.getBoolean("error")) { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); } else { SharedPreferences preferences = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("emailkey", email); editor.putBoolean("loggedIn", true); editor.apply(); Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); Intent intent = new Intent(MainActivity.this, ProfileActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } } catch (JSONException e) { e.printStackTrace(); } } @Override protected String doInBackground(Void... voids) { //creating request handler object RequestHandler requestHandler = new RequestHandler(); //creating request parameters HashMap<String, String> params = new HashMap<>(); params.put("email", email); params.put("password", password); params.put("token", token); //returing the response return requestHandler.sendPostRequest("http://192.168.43.17/fcmphpmysql/api/index.php", params); } } Login ul = new Login(); ul.execute(); } }
So, whats new things we have added in above file? We have created a new method LoginRegister()
which is doing the task of send request to the PHP
api (which we are going to develop further). we are also sending POST
parameters such as email, password and token, which will be saved in the database using PHP
. In the onPostExecute()
method, we are getting a response from the server. If the request processed successfully, then we are saving the current user details in SharedPreferences
and opening a new profile activity. If you are unaware of what is SharedPreferences
, then I recommend to have a look at SharedPreferences in android tutorial , to know about it in details.
We are using the overrided onStart()
method, in which we have made a logic. We have set intent flags which will send the user to ProfileActivity if it is already logged in, bypassing the login page. However, We will code the ProfileActivity later.
Building mechanism to handle requests
Before that, let us create the RequestHandler.java
class, which we are using in the above code. It helps to send the request along with POST parameters. Hers’s the class.
package net.softglobe.fcmphpmysql; import android.util.Log; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import static android.content.ContentValues.TAG; public class RequestHandler { //this method will send a post request to the specified url //in this app we are using only post request //in the hashmap we have the data to be sent to the server in keyvalue pairs public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) { URL url; Log.i("Received URL: ",requestURL); StringBuilder sb = new StringBuilder(); try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); String response; while ((response = br.readLine()) != null) { sb.append(response); } } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } //this method is converting keyvalue pairs data into a query string as needed to send to the server private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } Log.i("post parameters: ",""+result.toString()); return result.toString(); } }
In above class, We are using HttpURLConnection
class, to create a connection and using HashMap for sending POST
parameters using key-value pairs. This is important as we are sending push notification in android using php mysql.
Note: If you are new with the url connection and sending POST request parameters to server, then I recommend you to please have a look at the Android Login Registration using PHP and MySQL tutorial first. These things are explained in details there.
Now, lets create a new empty activity ProfileActivity
. It will be opened once the user either registers, or on the successful login. Lets first code activity_profile.xml
as below.
<?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:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ProfileActivity" android:layout_margin="10sp" android:orientation="vertical"> <TextView android:id="@+id/welcome_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Welcome, " android:textSize="30sp" /> <Button android:id="@+id/logoutbtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Logout" android:textAllCaps="false"/> </LinearLayout>
Creating Profile page
Now, lets code its java file ProfileActivity.java
with the following code in it.
package net.softglobe.fcmphpmysql; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ProfileActivity extends AppCompatActivity { TextView welcome; Button logout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); SharedPreferences preferences = getSharedPreferences(MainActivity.SHARED_PREF_NAME, MODE_PRIVATE); String email = preferences.getString("emailkey","NA"); welcome = findViewById(R.id.welcome_email); welcome.setText("Welcome, "+email); logout = findViewById(R.id.logoutbtn); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences preferences = getSharedPreferences(MainActivity.SHARED_PREF_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.apply(); Intent intent = new Intent(ProfileActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }); } @Override protected void onStart() { super.onStart(); SharedPreferences preferences = getSharedPreferences(MainActivity.SHARED_PREF_NAME, MODE_PRIVATE); boolean isLoggedIn = preferences.getBoolean("loggedIn",false); if (!isLoggedIn){ Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } } }
In the above file, we are simple extracting the saved email from SharedPreferences
and showing it to the user. Furthermore, we are also creating a logout button. When it is clicked, we will clear all the key-value pairs in SharedPreferences
and redirect user to login page.
Building Service for Receiving push Notifications
Above all, as we are using FCM for notifications, then our app should have some service which should trigger the notification received event and display the notification. Thus, to accomplish this task, create a new java class MessagingService.java
and paste the following code in it.
//This method is a messaging service, which will be called when the application received the notification package net.softglobe.fcmphpmysql; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class MessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); if (remoteMessage.getNotification() != null){ String title = remoteMessage.getNotification().getTitle(); String text = remoteMessage.getNotification().getBody(); //calling method to display notification NotificationHelper.displayNotification(getApplicationContext(), title, text); } } }
The above extends FirebaseMessagingService
. We have to handle the event of message received. Therefore, We are overriding the method onMessageReceived
. Furthermore, we are getting the details of message title and body. With these details, we are calling the method displayNotification
from the NotificationHelper
class, which will display the notification.
Now, we just have to do the last step for android module. Head over to AndroidManifest.xml
and Paste the below code just before the closing of </application>
tag.
<service android:name=".MessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
The above is a FCM service which keeps the track of message received from Firebase cloud server. Also, add the Internet permission in it, as we will need the internet access.
<uses-permission android:name="android.permission.INTERNET"/>
Thus, the whole AndroidManifest.xml
will look like as follows.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.softglobe.fcmphpmysql"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".ProfileActivity"></activity> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> </application> </manifest>
That’s it for android app. Now,we will move towards the server side module. It is simple, and quick. Just make sure that you have at least basic knowledge of PHP and MySQL before moving further. If you feel a need to learn PHP, then you can visit the PHP tutorials category.
2. Server (PHP MySQL) Module
Secondly, Setting up the server side things to get our app work quickly and send push notification in android using php mysql.
Setting up database
Here, we have to show notification to the intended user. Thus, to identify the unique user, we will create user accounts to implement sending notifications to unique user. Thus, create a database of any name of your choice. Furthermore, lets create a new table in it having fields as id, email, password, token. You can use the following query to create the table.
DROP TABLE IF EXISTS `fcm`; CREATE TABLE IF NOT EXISTS `fcm` ( `id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(100) NOT NULL, `password` varchar(255) NOT NULL, `token` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Now, we will move towards the api part. For that, we have to make a PHP file which will login or signup the user and save the details along with the toke generated. Furthermore, We will use that token to uniquely identify the device and send notifications to it.
Creating PHP API
In order to send push notification in android using php mysql, we have to create a PHP api. Thus create a folder fcmphpmysql in wamp if you are using Wampserver or create in htdocs, if you are using Xamppserver. First of all, create a config.php
file in it as follows, for connection with database.
<?php //Remember to change below values with yours $servername = "localhost"; $username = "root"; $password = ""; $dbname = "newdb"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); ?>
Again create a new folder in it, name it as ‘api’. Create a file index.php
in it. Put the following code in it.
<?php include "../config.php"; //an array to display response $response = array(); if(isset($_POST['email']) && isset($_POST['password']) && isset($_POST['token'])){ $email = $_POST['email']; $password = $_POST['password']; $token = $_POST['token']; $fetchuser = $conn->prepare("SELECT password FROM fcm WHERE email=?"); $fetchuser->bind_param("s",$email); $fetchuser->execute(); $fetchuser->store_result(); $fetchuser->bind_result($db_password); $fetchuser->close(); if ($db_password != null){ if(password_verify($password, $db_password)){ $updtuser = $conn->prepare("UPDATE fcm SET token=? WHERE email=?"); $updtuser->bind_param("ss",$token, $email); if($updtuser->execute()){ $response['error'] = false; $response['message'] = "Login Successful"; } else { $response['error'] = true; $response['message'] = "Login Failed"; } } else { $response['error'] = true; $response['message'] = "Invalid password"; } } else { $password_encrypted = password_hash($password, PASSWORD_DEFAULT); $saveuser = $conn->prepare("INSERT INTO fcm(email, password, token) VALUES (?,?,?)"); $saveuser->bind_param("sss",$email, $password_encrypted, $token); if($saveuser->execute()){ $response['error'] = false; $response['message'] = "Registered Successfully"; } else { $response['error'] = true; $response['message'] = "Registration failed"; } } } else { $response['error'] = true; $response['message'] = "Insufficient parameters"; } echo json_encode($response); ?>
The above file will receive the POST parameters sent by the app. The parameters required are email, password and token. The above code will register a new user and if the user already exists, it logs in the user. While registering, the FCM token will be saved in the database and will be kept updated with each login. It will send an appropriate JSON
response to the app.
Sending Request to FCM Server
Now, we are done with setting api. For sending push notification in android using php mysql, we have to send server request to FCM. Thus, we just have to create a last file of this tutorial that is, notification.php
in our previously created folder fcmphpmysql. Paste the following code in it.
<?php include "config.php"; ?> <html> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <p class="display-2 text-center">Send Notification</p> <form action="" method="post"> <div class="form-group"> <label for="ids">Select Email:</label> <select class="form-control" id="ids" name="email" required> <option value="">Select Email</option> <?php if($result = $conn->query("SELECT * FROM fcm")){ while($row = $result->fetch_assoc()){ $email = $row['email'];?> <option value="<?php echo $email; ?>"><?php echo $email; ?></option> <?php } } ?> </select> </div> <div class="form-group"> <label for="title">Email Title:</label> <input type="text" class="form-control" placeholder="Enter Title" name="title" id="title" required> </div> <div class="form-group"> <label for="msg">Enter Message:</label> <input type="text" class="form-control" placeholder="Enter Message" name="message" id="msg" required> </div> <button type="submit" name="submitbtn" class="btn btn-primary">Submit</button> </form> </div> </body> </html> <?php if(isset($_POST['submitbtn'])){ $email = $_POST['email']; $title = $_POST['title']; $message = $_POST['message']; $fetchToken = $conn->prepare("SELECT token FROM fcm WHERE email=?"); $fetchToken->bind_param("s",$email); $fetchToken->execute(); $fetchToken->store_result(); $fetchToken->bind_result($token); $fetchToken->fetch(); $fetchToken->close(); $result = push_notification_android($token, $title, $message); $obj = json_decode($result); if($obj->success>0){ ?> <div class="container"> <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert">×</button> Notification sent successfully! </div> </div> <?php } else {?> <div class="container"> <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert">×</button> Failed to send notification </div> </div> <?php } } function push_notification_android($device_id, $title, $message){ //API URL of FCM $url = 'https://fcm.googleapis.com/fcm/send'; /*api_key available in: Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key*/ $api_key = 'AAAA......Rx'; //Replace with yours $target = $device_id; $fields = array(); $fields['priority'] = "high"; $fields['notification'] = [ "title" => $title, "body" => $message, 'data' => ['message' => $message], "sound" => "default"]; if (is_array($target)){ $fields['registration_ids'] = $target; } else{ $fields['to'] = $target; } //header includes Content type and api key $headers = array( 'Content-Type:application/json', 'Authorization:key='.$api_key ); $ch = curl_init(); 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_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); if ($result === FALSE) { die('FCM Send Error: ' . curl_error($ch)); } curl_close($ch); return $result; } ?>
Let us understand what we are doing in above class. The HTML fields above are designing the form which have three fields. First one is a menu to select the emails of users, which we have registered though one or more devices. The PHP code will fetch all the emails and displays the list dynamically. The second and third fields are title and body of notification respectively. After submitting the form. we are fetching the token relevant to email address selected. We have created a function push_notification_android()
which is taking three parameters as token, title and message. In it, we are creating an array of variables to send them to Firebase server.
We are using a curl request for that purpose. Thus, our request with the relevant parameters will be sent to Firebase server and the function will return the server’s response as a JSON
object. Finally, We are showing the relevant success or failure messages to the user.
Sending push notification in android using php mysql
That’s it! Finally, We are have finished with our project. Now lets try running the application. See the below screen of successful sending of notification.
Similarly, See the push notification in android using php mysql as follows.
Congratulations! You have made it possible. Lets clap for yourself. 🙂
Note: If you are running the application in android emulator and not getting the notification, then try running on real device. It may happen due to deprecated version of Google Play Services installed on emulator. Generally, we do not update the play services on emulators and we use the newer version in project development. So, this might cause issue.
If you have any questions about the tutorial, ask in the comments section below. Me, as your helping friend will try to resolve all your problems. 🙂 Alternatively, you can always download the source code for free from the below link.
6 thoughts on “Push Notification in Android using php mysql”