Push Notification in Android using php mysql

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.

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.

push notification in android using php mysql

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.

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.

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.

That all about designing. Now, lets build the back end tasks. Thus, open MainActivity.java and paste the following code in it.

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.

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.

Creating Profile page

Now, lets code its java file ProfileActivity.javawith the following code in it.

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.

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.

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.

Thus, the whole AndroidManifest.xml will look like as follows.

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.

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.

Again create a new folder in it, name it as ‘api’. Create a file index.php in it. Put the following code in it.

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.

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.

Push Notification in Android using php mysql

Similarly, See the push notification in android using php mysql as follows.

Push Notification in Android using php mysql

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.

Download Source Code

5 thoughts on “Push Notification in Android using php mysql

    1. Ashish Joshi says:

      Hey Mayur, please confirm if your device has access to google play services. If it does, then i suggest you to check whether your device is generating the token and your database is saving the same.

  1. t
    taha says:

    FirebaseInstanceId is no longer supported so what is the solution my friend please

    .addOnCompleteListener(new OnCompleteListener() {
    public void onComplete(@NonNull Task task) {
    if (task.isSuccessful()){
    token = task.getResult().getToken();
    } else {
    Toast.makeText(MainActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.