Android push service, implementing the gcm server

2019-03-02 12:59发布

问题:

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 created my google cloud project, enabled android push notif.s and got my Project Number, Project ID and API Key.

So far so good, then I wanted to get to the implementing the server side of it but for some reason I have no idea what I should do, where should I write the code? Is it going to be a web service like restful? I have been digging the http://developer.android.com/google/gcm/ccs.html but I got no good outcome of what I should do. I haven't found a proper tutorial about this on the internet too, they are all about the deprecated versions of push like C2DM. I'd really appreciate the help. Regards.

Note: I'm using Mssql.

回答1:

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

<?php
   $regidOne="Your regid for one phone/project combination";
   $apiKey = "Your API KEY"; 
?>

Secondly the entry.php which holds the form and the button for the message

entry1.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<?php session_start();?>
<body>

<br>
Compose a message below

  <form action="send_it.php" method="post">
    <div id="a" align="left">   
     <P><TEXTAREA name="message" rows="3"   cols="58"></TEXTAREA><br>
            <INPUT type="submit" value="Click to send the message">
     </P>
    </div>
  </form>

<?php 
  $ret=$_SESSION['retval'];
  echo "Last message status: "; 
  echo $ret; 
  echo"<br><br>";
?>
</body>
</html>

Lastly the file (send_it.php) which does the work via curl

<?php session_start();
   require 'vals.php';
   $randomNum=rand(10,100); 
   $registrationIDs[] = $regidOne;
   $message =  strip_tags($_POST['message']);


   $url = 'https://android.googleapis.com/gcm/send';
   $fields = array(
           'registration_ids' => $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 "<p>";
   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 "<br>"; echo "JSON parsed"; echo "<br>";
   $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