Sending Push Notifications to Multiple Android Devices Using Gcm

sending push notifications to multiple android devices using GCM

Here I rewrote the php using mysql rather than retrieving the keys from file. In this case, I retrieve all the regIds from the table and put them in an array and pass it to sendPushNotification function to push the message to all. here you have 2 files, one for connect to database and one for GCM:

connect.php:

<?php

$db_host = "localhost";
$db_user = "root"; //change to your database username, it is root by default
$db_pass = ''; //change to your database password, for XAMPP it is nothing for WAMPP it is root
$db_db = 'gcmFirst'; //change to your database name

if(!@mysql_connect($db_host, $db_user, $db_pass) || !@mysql_select_db($db_db)) {
die('couldnt connect to database ' .mysql_error());
}

?>

gcm.php

<?php
require 'connect.php';

function sendPushNotification($registration_ids, $message) {

$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);

define('GOOGLE_API_KEY', 'AIzaSyCjctNK2valabAWL7rWUTcoRA-UAXI_3ro');

$headers = array(
'Authorization:key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
echo json_encode($fields);
$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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());

curl_close($ch);
return $result;

}

$pushStatus = '';

if(!empty($_GET['push'])) {

$query = "SELECT regId FROM users";
if($query_run = mysql_query($query)) {

$gcmRegIds = array();
while($query_row = mysql_fetch_assoc($query_run)) {

array_push($gcmRegIds, $query_row['regId']);

}

}
$pushMessage = $_POST['message'];
if(isset($gcmRegIds) && isset($pushMessage)) {

$message = array('message' => $pushMessage);
$pushStatus = sendPushNotification($gcmRegIds, $message);

}
}

if(!empty($_GET['shareRegId'])) {

$gcmRegId = $_POST['regId'];
$query = "INSERT INTO users VALUES ('', '$gcmRegId')";
if($query_run = mysql_query($query)) {
echo 'OK';
exit;
}
}
?>

<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method = 'POST' action = 'gcm.php/?push=1'>
<div>
<textarea rows = 2 name = "message" cols = 23 placeholder = 'Messages to Transmit via GCM'></textarea>
</div>
<div>
<input type = 'submit' value = 'Send Push Notification via GCM'>
</div>
<p><h3><?php echo $pushStatus ?></h3></p>
</form>
</body>
</html>

all you have to do is create a database that has a users table with id, regId and name as columns.

Hope this is what you are looking for

Send GCM notifications to multiple devices using PHP

You must get result in JSON Array. Try the following code:

<?php

if($_SERVER['REQUEST_METHOD']=='GET'){

$tags = $_GET['tags'];
// Replace with the real server API key from Google APIs
$apiKey = "YOUR_API_CODE";

$message = "Hello Raja";

// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';

require_once('dbConnect.php');

$user_ids = array();

foreach ($_REQUEST['tags'] as $key => $val) {
$user_ids[$key] = filter_var($val, FILTER_SANITIZE_STRING);
}
$tagss = "'" . implode("','", $user_ids) . "'";
$sql = "SELECT user_tags.user_id AS userID , gcm_token.regtoken AS regToken
FROM user_tags,gcm_token
WHERE tags IN ({$tagss}) AND user_tags.user_id=gcm_token.user_id";

$r = mysqli_query($con,$sql);

$result = array();

//looping through all the records fetched

while ($row = mysqli_fetch_array($r)) {
$result[] = $row['regToken'];
}

//Displaying the array in json format

//echo json_encode(array('result'=>$result));

echo json_encode(($result));

$registrationIDs = ($result);

//echo json_encode(array('result'=>$result));

$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'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);
//curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POST, true);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));

// Execute post
$result = curl_exec($ch);

// Close connection
curl_close($ch);
echo $result;
//print_r($result);
//var_dump($result);
}

?>

Notification on multiple android phones using GCM and web services + database data

I have been there ,done that! The way you should to proceed is:-

  1. Create your website backend, a web service connected to a database(You need to use and know SQL for this part). Define your database accordingly. PHP is the easiest way to get started. Look at the GCM backend tutorials on Google.
  2. Create your mobile application which has google play services enabled to use GCM. Implement GCM in your android app following the tutorial at the Official Android Developer website. You need to create an XMPP or RESTful service to communicate with your server. Your server needs to support XMPP to communicate better with Google. HTTP(GET/POST/PUT) is a dirty alternative to get working when you do not have a VPS setup for languages like Java(Most hosting companies allow only PHP,HTML,JavaScript etc on shared hosting).Depending on your scale of operation you may have to rent a Virtual Private Server(VPS) for your web service.
  3. Create a private backend application(can be web or a desktop application) to upload your offers and so on. Examples on www.androhive.info
  4. Make sure you got steps 1,2,3 correct.
  5. Test your mobile application.

The idea can be pictorially represented as :-
GCM Architecture

GCM: Using same account on multiple devices - what happens?

What happens when I send to one of the regid a message - will the second get the message too?

Well, no. This is because GCM not only takes into account just the Google account that you use on your phone but also identifies the particular device and the particular app you are running on it. GCM id is unique for a any given app on any given device. That is how the cloud identifies which device to push notifications to. So even if you sign in to two different devices with the same account, both will register with different keys. You use this key to identify the individual device/app.

Go to the official documentation on this to get the full info.

When sending a push notification to multiple Android devices how can I detect which specific device(s) have had the app uninstalled?

If you are sending push notifications to more than one device (registration_ids) in a single request then your best bet is to use the JSON interface as opposed to the plain-text interface. The JSON interface will respond with an object showing the number of successes and failures along with a list of results objects for each device you sent a push notification to.

Unfortunately, the example in the documentation here: http://developer.android.com/google/gcm/http.html shows an incorrect format.

Here is an example response:

{
"multicast_id":123456,
"success":1,
"failure":1,
"canonical_ids":0,
"results":[
{"message_id":"0:abcde"},
{"error":"NotRegistered"}
]
}

You can first check the number of failures and, if there failures, iterate through the list of results. The number of elements in results will be the same as the number of push messages you sent and the order is the same as the registation_ids specified in the request. You can now find the errors and tally which devices are NotRegistered or are even an InvalidRegistration; both meaning that the registation_id is no longer valid and your server should stop sending it push notifications.

Max number of devices can GCM send push notifications to

Based on the Official Google Documentation, specifies a list of devices (bases on registration tokens or IDs) receiving a multicast message. It must contain atleast 1 and at most 1000 registration tokens.
For multicast messaging, not for single recipients. Multicast messages (sending to more than 1 registration tokens) are allowed using HTTP JSON format only.

You may check the Official Google documentation here: https://developers.google.com/cloud-messaging/http-server-ref



Related Topics



Leave a reply



Submit