Android Push Notification with Image using GCM, php & mysql Example Part 1

Please follow and like us:

android push notification with image example with php

Try latest Android Push Notification tutorial using Firebase Cloud Messaging (FCM)

Android Push Notification with Image using google cloud messaging (gcm) is useful to send Push Notification from Server to Android Application. Here in Android Push Notification with Image using GCM, php & mysql Example Part 1, we will start to setup server side logic by creating form with PHP and mysql database. Let’s explore Android Push Notification with Image Server side Example.

In Part 2, we will see Android portion for implementing Android Push Notification with Image in Android App. Before understanding server side logic, let’s first understand how google cloud messaging works.

Android Push Notification with Image

Step 1: Android device send sender id to GCM server for registering device

Step 2: GCM Server generate registration id for android device

Step 3: Now our device send registration id to server through API

Step 4: Server save registration id in database for future use

Step 5: For requesting push, our server send request with registration id to GCM server

Step 6: GCM server send push notification to android device based on registration id.

Let’s explore Server side logic step by step for sending Android Push Notification with image

1. Generating Google API Key

Google API key is required to communicate with GCM Server. GCM uses this API key to identify the your Server App. Follow the bellow steps to generating Google API key.

Step 1:First Open Google developers cloud console and create a new app. Or if you have already created app then select the app.

Step 2:Create new project and provide the name to it. Once project is created, goto project’s dashboard where you can find the details about your project. Copy Project Number for future use in Android App.

Step 3:Now open “Use Google APIs” from dashboard. In Mobile APIs, click on Cloud Messaging for Android and then enable the API by clicking on enable API button.

Step 4:Now click on Credentials on the left. You will be asked for create new credentials by showing multiple options. you need to choose API Key and then Server Key.

Step 5:You will get your API key on the dashboard. Save the API key we need it in our PHP project.

2. Designing MySQL Database

CREATE DATABASE push_demo;
 
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `registration_id` varchar(100) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

3. Creating PHP Rest API

<?php $server = "localhost"; $database = "ADD_DATABASE_NAME_HERE"; $username = "ADD_USERNAME_HERE"; $password = "ADD_PASSWORD_HERE"; $mysqlConnection = mysql_connect($server, $username, $password); if (!$mysqlConnection) { echo "Please try later."; } else { mysql_select_db($database, $mysqlConnection); } if ($_SERVER['REQUEST_METHOD'] == "GET") { // Get data $registration_id = isset($_GET['registration_id']) ? mysql_real_escape_string($_GET['registration_id']) : ""; // Insert data into data base $q = mysql_query("select * from user where registration_id='" . $registration_id . "'") or die(mysql_error()); $n = mysql_fetch_row($q); if ($n > 0) {
        $json = array(
            "status" => 2,
            "msg" => "UserID already added!"
        );
    } else {
        
        $sql = "INSERT INTO user (registration_id) VALUES ('$registration_id')";
        $qur = mysql_query($sql);
        if ($qur) {
            $json = array(
                "status" => 1,
                "msg" => "Done user id added!"
            );
        } else {
            $json = array(
                "status" => 0,
                "msg" => "Error adding user id!"
            );
        }
    }
} else {
    $json = array(
        "status" => 0,
        "msg" => "Request method not accepted"
    );
}

@mysql_close($conn);

/* Output header */
header('Content-type: application/json');
echo json_encode($json);

?>

Replace “ADD_DATABASE_NAME_HERE“, “ADD_USERNAME_HERE” and  “ADD_PASSWORD_HERE” with your database name, user name and password.
We need to call this API like this…

your root domain name/add_registration_id.php?registration_id=your registration id here

We will get three kind of status message

status 0: means there is something wrong with API call, error occurs while calling API

status 1: means registration id added successfully.

status 2: means registration id is already added in database.

4. Design and Build Android Push Notification With Image Form

@import url(https://fonts.googleapis.com/css?family=Roboto:300);
h1 {
    color:#ffffff;
    padding: 15px;
  font-family: "Roboto", sans-serif;
}
.login-page {
  width: 660px;
  padding: 8% 0 0;
  margin: auto;
}
#outputvalue {
 font-family: "Roboto", sans-serif;
    color: #4CAF50;
    text-align: center;
    margin: 10px 0px;
    font-size: 17px;
}
.form {
  position: relative;
  z-index: 1;
  background: #FFFFFF;
  max-width: 360px;
  margin: 0 auto 100px;
  padding: 45px;
  text-align: center;
  box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}
.form input {
  font-family: "Roboto", sans-serif;
  outline: 0;
  background: #f2f2f2;
  width: 100%;
  border: 0;
  margin: 0 0 15px;
  padding: 15px;
  box-sizing: border-box;
  font-size: 14px;
}
input[type=submit] {
  font-family: "Roboto", sans-serif;
  text-transform: uppercase;
  outline: 0;
  background: #4CAF50;
  width: 100%;
  border: 0;
  padding: 15px;
  color: #FFFFFF;
  font-size: 18px;
  -webkit-transition: all 0.3 ease;
  transition: all 0.3 ease;
  cursor: pointer;
}
.form button:hover,.form button:active,.form button:focus {
  background: #43A047;
}
.form .message {
  margin: 15px 0 0;
  color: #b3b3b3;
  font-size: 12px;
}
.form .message a {
  color: #4CAF50;
  text-decoration: none;
}
.form .register-form {
  display: none;
}
.container {
  position: relative;
  z-index: 1;
  max-width: 300px;
  margin: 0 auto;
}
.container:before, .container:after {
  content: "";
  display: block;
  clear: both;
}
.container .info {
  margin: 50px auto;
  text-align: center;
}
.container .info h1 {
  margin: 0 0 15px;
  padding: 0;
  font-size: 36px;
  font-weight: 300;
  color: #1a1a1a;
}
.container .info span {
  color: #4d4d4d;
  font-size: 12px;
}
.container .info span a {
  color: #000000;
  text-decoration: none;
}
.container .info span .fa {
  color: #EF3B3A;
}
body {
  background: #76b852; /* fallback for old browsers */
  background: -webkit-linear-gradient(right, #76b852, #8DC26F);
  background: -moz-linear-gradient(right, #76b852, #8DC26F);
  background: -o-linear-gradient(right, #76b852, #8DC26F);
  background: linear-gradient(to left, #76b852, #8DC26F);
  font-family: "Roboto", sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;      
}

In bellow code replace “ADD_DATABASE_NAME_HERE“, “ADD_USERNAME_HERE“,  “ADD_PASSWORD_HERE” and “ADD_GCM_API_KEY_HERE” with your database name, user name, password, GCM Push Notification API key.

<html>
   <head>
      <title>Android Push Notification With Image Example</title>
      <meta charset="UTF-8">
      <link href='style.css' rel='stylesheet' type='text/css'>
      <script type="text/javascript">
         function validate()
         {
            if( document.myForm.title.value == "" )
            {
               alert( "Please provide title!" );
               document.myForm.title.focus() ;
               return false;
            }
            
            if( document.myForm.message.value == "" )
            {
               alert( "Please provide message!" );
               document.myForm.message.focus() ;
               return false;
            }
            
         if( document.myForm.image.value == "" )
            {
               alert( "Please provide image url path!" );
               document.myForm.image.focus() ;
               return false;
            }
            return( true );
         }
        
      </script>
   </head>

   <body>

<?php $server = "localhost"; $database = "ADD_DATABASE_NAME_HERE"; $username = "ADD_USERNAME_HERE"; $password = "ADD_PASSWORD_HERE"; error_reporting('E_ALL ^ E_NOTICE'); if (isset($_POST['submit'])) { $mysqlConnection = mysql_connect($server, $username, $password); if (!$mysqlConnection) { echo "Please try later."; } else { mysql_select_db($database, $mysqlConnection); } $title = $_POST['title']; $message = $_POST['message']; $image = $_POST['image']; $q = mysql_query("SELECT * FROM user"); $registrationIds = array(); while ($row = mysql_fetch_array($q)) { //Creates a loop to loop through results $registrationIds[] = $row['registration_id']; } $outputvalue = "Push Notification Sent"; define('API_ACCESS_KEY', 'ADD_GCM_API_KEY_HERE'); $msg = array( 'message' => $message,
        'title' => $title,
        'image_url' => $image
    );
    
    $fields = array(
        'registration_ids' => $registrationIds,
        'data' => $msg
    );
    
    $headers = array(
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
    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_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    curl_close($ch);
    
}
?>
<div class="login-page" >
<h1 text-color:"#ffffff">
         <center>Android Push Notification with Image</center>
</h1>

<div class="form">
<form class="login-form" action="#" method="post" name="myForm" onsubmit="return(validate());" >
               <input type="text" placeholder="Title" name="title" id="title"/>
               <input type="text" placeholder="Message" name="message" id="message"/>
               <input type="text" placeholder="Image URL Path" name="image" id="image"/>
               <input type="submit" name="submit" id="submit" value="Submit">
<div id="outputvalue"> <?php print_r($outputvalue); ?> </div>
            </form>
         </div>
      </div>
   </body>
</html>

Android Push Notification with Image

 

Hope you like our simple tutorial for setting server side logic for Android Push Notification with Image Example. In next tutorial we are going to discuss about Android side logic for getting Push Notification with image in your Android Application.

nirav kalola