I am all new to the android push world and I have been struggling a little, for couple of days now. I created and implemented the GCM client side of it without a problem. I also
I thought that there was a tutorial in the developer docs on which I based my server. Now that I look for it, I can't find it, so I'll post a cut down version of my code.
I have a Raspberry Pi as a server, running Apache with PHP and a MySQL database. I select a device and a project combination and send a message to that app on that device via a web page. I do a select in the PHP, based on the project ID and the owner/device to get me a registration ID to which the message will be sent.
To keep this answer simple, I'll show you how to send a message to a device where the RegId and the API Key are hard coded. You can put your own DB stuff around it later.
Firstly the vals.php file which holds my/your secret hard coded stuff
Secondly the entry.php which holds the form and the button for the message
entry1.php
Compose a message below
";
?>
Lastly the file (send_it.php) which does the work via curl
$registrationIDs,
'data' => array( "message" => $message),
'delay_while_idle'=> false,
'time_to_live' => 86400,
'collapse_key'=>"".$randomNum.""
);
$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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo "Your message has been sent, the results from the Cloud Server were :\n";
echo "";
echo $result;
$targets = array("{", "\"");
$interim = str_replace($targets, " ", $result);
$pieces = explode(",", $interim);
$pos = strpos($result, 'multicast');
if ($pos === false) {
$ret = "Failed";
$_SESSION['retval']=$ret;
} else {
$ret = "Sent OK, ";
$_SESSION['retval']=$ret.$pieces[0];//Just the multicast id
}
echo "
"; echo "JSON parsed"; echo "
";
$jres = json_decode($result);
print_r($jres);
$retloc = 'Location:'.$_SERVER['HTTP_REFERER'];
if(!strstr($message, "skipheader")) {
header($retloc);
// COMMENT OUT THE LINE ABOVE TO SEE THE OUPUT, OTHERWISE RETURN TO MESSAGE I/P FORM PAGE
}
?>
You will need an Apache web server with curl support. These scripts work fine on both my raspberry pi and my Windows machine. The html/php may be a bit on the ropey side, as I've done a lot of cutting to take out my DB stuff, but it does at least work. I hope it's usful