Android push notification is very common today most of application use this service to let user know new message or event according to functionality of their app and service. In this post i will explain you how we can create a push notification service for android application and how we setup a CRON jobs in hosting to run php script automatically with simple example.
rest-gcm-cron

Before start creating a web service for push notification you need some basic knowledge of creating web service please read my last post of creating a web service in this link. Now first i give you small overview of Google Cloud Messaging for Android (GCM). Google cloud messaging is a service provided by a google to send message to target device which is powered by android operating system. In simple word GCM help us to send notification  and data to particular device using targeted device id. GCM use unique device id which is generated by application/device and send that id to web service where we save that id and when ever we need to send notification to that particular device which is associated with that id we can ping GCM server with that id and message and GCM deliver that message to that device so simple. Code: I create a simple web service example which help you to understand that how this thing work. Create DB:

--
-- Database: `gcm`
--

-- --------------------------------------------------------

--
-- Table structure for table `gcm`
--

CREATE TABLE IF NOT EXISTS `gcm` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `gcm` varchar(500) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Create connection to database:

<?php
$con = mysql_connect("localhost", "root", "");
$db = mysql_select_db("gcm", $con);
?>

Now we going to save GCM id which is generated by android application in database . service.php

<?php
if($_SERVER['REQUEST_METHOD'] !== "POST"){exit();}

include_once 'conn.php';

$json = '';

$gcm = $_POST['gcm'];
if(empty($gcm)){
	$json = array('status' => "0", "message" => "Unable to get device ID.");
}else{
	// Insert data to database
	$sql = "insert into gcm set gcm='$gcm'";
	if(mysql_query($sql)){
			$json = array('status' => $gcm, "message" => 'Done');
		}else{
			$json = array('status'=> 0, "message" => 'Error inserting data to database.');
		}
	}
mysql_close();
/* Output header */
header('Content-type: application/json');
echo json_encode($json);

I am using Advance REST Client to test my web service . Now we need to Google Cloud Messaging API key to send notification to device.

  1. Login to your Google Api Console.
  2. Click on services link and turn on your Google Cloud Messaging for Android.
  3. Now click on API Access and you will find your API key right there.

I am using google GCM class to send notification to device GCM.php

<?php
 
class GCM {
 
    //put your code here
    // constructor
    function __construct() {
         
    }
 
    /**
     * Sending Push Notification
     */
    public function send_notification($registatoin_ids, $message) {
        // include config
        define('GOOGLE_API_KEY', 'YOUR Google GCM api key');
 
        // Set POST variables
        $url = 'https://android.googleapis.com/gcm/send';
 
        $fields = array(
            'registration_ids' => $registatoin_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);
        echo $result;
    }
 
}
 
?>

Send notification to device SendNotice.php

<?php
    include_once 'GCM.php';
 
    $gcm = new GCM();
 
    $registatoin_ids = "Device ID";
    $message = array("message" => "Love think code!!");
 
    $Ping = $gcm->send_notification($registatoin_ids, $message);
 
    echo $Ping;

?>

 Setting up a CRON job: I create a simple code in which i read content from fiile and increase the value by one every time when ever i run php code the file value is increase by one step 1: create a text file name as cron.txt. step 2: php code: corn.php

<?php
/*echo '<pre>';
print_r($_SERVER);
exit(); */
//$file = fopen('cron.txt', 'wb');
$file = fopen('cron.txt', 'r');
$data = fread($file, filesize('cron.txt'))+1;
fclose($file);
$file = fopen('cron.txt', "w");
$up = fwrite($file, $data);
fclose($file);
echo $data;
?>

Step 3. Setting up a cron job:

  • Login to your hosting cPanel i am using godaddy to run my cron job.
  • Find cron jobs option and click on it.
  • cronjob
  • Set time/interval to run your cron job.
  • crontime
  • Write down command to run the particular script after set interval eg. CMD: php /home/anehthakur/public_html/rtuts.in/cron/cron.php
  • Note that you need to set complete location of file to execute.

Happy coding!!!.

 

Posted in: php