Implementing Android Push Notification using PHP,MYSQL and GCM-II

php_mysql_push_notification_android_gcm

In the last post we checked how to work with GCM on the client side.Now in this post we are going to post notification through PHP and MySql DB.


The Mysql DB will be used to store token ID generated from GCM..PHP will bind the Android and Mysql to send PHP notification to devices.


Part 1:Implementing push notification using GCM


lets get Started!


First we need to setup our Mysql DB to store token


Create a DB "gcmdb"


create database gcmdb;


Next we need to create table


Create table deviceinfo(tokenid varchar2(250) not null);


Next we need to create our php files, we are going to use PDOconnections


creating PDOConnections.php



<?php
$dbName = "gcmdb";
$user = "system";
$pwd = "1234";
$host = "localhost";
$cnn = new PDO('mysql:dbname='.$dbName.';host='.$host, $user, $pwd);

Fetching and Sending the request to GCM


Next we have to post request to server using gcm.php which will insert the token and retrieve it while sending notification.



prepare($query);
 $stmt->bindParam(1, $token);
 $stmt->execute();
 echo("Insert success");
}
//Check exists token
function isExistToken($cnn, $token)
{
 $query = "SELECT * FROM deviceinfo WHERE TOKENID = ?";
 $stmt = $cnn->prepare($query);
 $stmt->bindParam(1, $token);
 $stmt->execute();
 $rowcount = $stmt->rowCount();
 return $rowcount;
}
?>

The Notification Page! Next creating the send notification page where we will send the notification messages to devices.


<?php
include("PDOConnection.php");
define('GOOGLE_API_KEY', 'AIzaSyCBV6kqW1sPsftrcnXeXqaJ8vZ2JbVQPyo');//Replace with your Key

$pushStatus = '0';;

if(isset($_POST['submit'])) {
 $gcmRegIds = array();
    $sql = "SELECT TOKENID FROM DEVICEINFO";
    $result = $cnn->query($sql);
 while($row = $result->fetch(PDO::FETCH_ASSOC))
 {
  array_push($gcmRegIds, $row["TOKENID"]);
 }
    $pushMessage = $_POST['message'];
    if(isset($gcmRegIds) && isset($pushMessage)) {
        $message = array('message' => $pushMessage);
        $pushStatus = sendPushNotification($gcmRegIds, $message);
    }   
}

function sendPushNotification($registration_ids, $message) {
            // Set POST variables
        $url = 'https://android.googleapis.com/gcm/send';
  $fields = array(
            'registration_ids' => $registration_ids,
            'data' => $message,
        );
        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();
 
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
 
        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        // Close connection
        curl_close($ch);
  return $result;
}

?>
<html>
    <head>
        <title>GCM Server</title>
    </head>
    <body style="text-align:center;color:white">
 <div style="background-color:#F2425A;height:100px;padding-top:15ppx;padding-bottom:15px;margin-top:-45px;width:100%">
 <h1>AndroidXU</h1>
   <h2 >Google Cloud Messaging (GCM) Server</h2>
   </div>
    <form method = 'POST' action = ''>
        <div style="padding-top:10px">
            <textarea rows = 6 name = "message" cols = 50 placeholder = 'Messages send to all device in database via GCM'></textarea>
        </div>
        <div style="margin-top:10px" >
            <input type = 'submit' name="submit" value = 'Send Notification' style="background-color:#F2425A;color:#fff;padding:5px 5px 5px 5px;border:none">
        </div>
        <p>
   <h3>
   <?php
    if('0' != $pushStatus)
    {
     $obj = json_decode($pushStatus);
     if($obj != null)
     {
      echo("<div style='color:green'>");
      echo("<p style='color:red'>Status:</p>");
      echo("Success:".$obj->success);
      echo("&nbsp;&nbspFailure:".$obj->failure);
      echo("</div>");
     }
     else
     {
      echo("<div style='color:red'>".$pushStatus."</div>");
     } }
   ?>
   </h3>
  </p>
    </form>
    </body>
</html>
One you hit the URL: http://localhost/gcm/gcm.php. You can see the below page.


GCM_push_notification


We need to send the request from our android code to PHP usng the token generated.

Finally Modifying the Java intent Service class

We are going to use the code which we used in previous post in part I

we are going to modify the GCMRegistrationIntentservice.java
if the token is already generated we will use shared preferances

package androidgreeve.android.com.gcmpushnotify;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by venkatesh on 15-05-2016.
 */
public class GCMRegistrationIntentService extends IntentService {
    //Assigning success and failure Messages
    public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";
    public static final String REGISTRATION_ERROR = "RegistrationError";
    public static final String TAG = "GCMTOKEN";
    public GCMRegistrationIntentService() {
        super("");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        registerGCM();
    }

    private void registerGCM() {
        SharedPreferences sharedPreferences = getSharedPreferences("GCM", Context.MODE_PRIVATE);//Define shared reference file name
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Intent registrationComplete = null;
        String token = null;
        try {
            InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
            token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            Log.w("GCMRegIntentService", "token:" + token);
            //notify to UI that registration complete success
            registrationComplete = new Intent(REGISTRATION_SUCCESS);
            registrationComplete.putExtra("token", token);

            String oldToken = sharedPreferences.getString(TAG, "");//Return "" when error or key not exists
            //Only request to save token when token is new
            if(!"".equals(token) && !oldToken.equals(token)) {
                saveTokenToServer(token);
                //Save new token to shared reference

                editor.putString(TAG, token);
                editor.commit();
            } else {
                Log.w("GCMRegistrationService", "Old token");
            }
        } catch (Exception e) {
            Log.w("GCMRegIntentService", "Registration error");
            registrationComplete = new Intent(REGISTRATION_ERROR);
        }
        //Send broadcast
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void saveTokenToServer(String token){
        Map paramPost = new HashMap();
        paramPost.put("action","add");
        paramPost.put("tokenid", token);
        try {
            String msgResult = getStringResultFromService_POST("http://192.168.209.2/gcm/gcm.php", paramPost);
            Log.w("ServiceResponseMsg", msgResult);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public String getStringResultFromService_POST(String serviceURL, Map<String, String> params) {
        HttpURLConnection cnn = null;
        String line = null;
        URL url;
        try{
            url = new URL(serviceURL);
        } catch (MalformedURLException e){
            throw  new IllegalArgumentException("URL invalid:"+serviceURL);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        //Construct the post body using the parameter
        while (iterator.hasNext()){
            Map.Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
            if(iterator.hasNext()){
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString(); //format same to arg1=val1&arg2=val2
        Log.w("AccessService", "param:" + body);
        byte[]bytes = body.getBytes();
        try{
            cnn = (HttpURLConnection)url.openConnection();
            cnn.setDoOutput(true);
            cnn.setUseCaches(false);
            cnn.setFixedLengthStreamingMode(bytes.length);
            cnn.setRequestMethod("POST");
            cnn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            //Post the request
            OutputStream outputStream = cnn.getOutputStream();
            outputStream.write(bytes);
            outputStream.close();

            //Handle the response
            int status = cnn.getResponseCode();
            if(status!=200){
                throw  new IOException("Post fail with error code:" + status);
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(cnn.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine())!=null){
                stringBuilder.append(line+'\n');
            }
            return stringBuilder.toString();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

check the logcat completely to identify flow,if you are facing difficulty try to uninstall app from device and run again.

If you are facing any issue feel free to comment below.

Like,Share and suggest if you want it to be covered  and happy Coding!

Comments

Popular posts from this blog

Android Bottom Navigation Bar tutorial with Fragments

The Ultimate guide On Jupyter Notebook[Part-2]-The Markdown

Pandas in Python for Data Analysis with Example(Step-by-Step guide)