Android Question GCM Server Side

Harris

Expert
Licensed User
Longtime User
Has anyone created a fully functional GCM server side app they are willing to share (PHP and MySql)?
I have read all the posts but it seems a bit overwhelming to put the bits and pieces all together.

I have a nice client created (willing to share) that pops up incoming messages (or sets notifications). Stores data to DB, has Inbox, Outbox (for replies) and App Options (TTS, auto delete old messages). Replies are sent to a server using RDC. I use it as an add-on to my main apps. Back returns to whatever called it.

Thanks

GCM_client.png
 
Still hoping someone has server side solution...
 
Upvote 0
in the gcm tutorial is a server-side-php script included. I did it with this script. Ok, little changes due to my needs (i have myown sender-script which knows the names of the destinations and their Google GCM-Registration-IDs they got after they register their names.)

You should go through the GCM-tutorial and build your GCM-system with that...

Maybe you want to show us more of the GCM-stuff you have done so far (you b4a-code/project export as zip, your serverside registrationscript, your sending script...
 
Upvote 0
Ok, I shall try. Frankly, just lazy and need the nudge... (with so much to accomplish).

Attached is my client - without sender id.
 

Attachments

Upvote 0
Ok, I shall try. Frankly, just lazy and need the nudge... (with so much to accomplish).

See here for sample php-file. This should be run on your webserver and should have access to an mysql-database.

with the url you provided in your code it can not work with registering to 100%...
You dont have access to the database the php which is called in cour code. THAT´s the point.
So, if you maybe make a register successfully you dont can send messages to this device cause the registrationid is stored in the dtabase which is created with the php-file (see link)...

Come on... It´s not that hard to manage! ;-)
 
Upvote 0
Ok, managed to move off of Erel's board.

I modified the the registration script (c2dm_board.php) to use my "devices" table. Each android device is registered to my server with a unique ID (based on device serial number). I also modified my client to use the device serial for registering. All is well. I can send messages to my device using the batch file from my desktop, with the new url in config.txt...

Now the issue is (and always was) sending a message from my server to the device - avoiding the send batch file...

I used the following code from example provided (modified with $mysqli)

I call this function with: sendGCM("015d24a4092c1345", "This is a test from server", $mysqli);
yet, nothing happens.... (no message sent to device). Obviously missing something here... Maybe my server doesn't support curl?

Code: Copy
function sendGCM($UserID, $message, $mysqli) {
    $query = "SELECT id From devices Where name=$UserID";
    $row = mysql_fetch_object(mysql_query($mysqli->$query));
  
    // Replace with real BROWSER API key from Google APIs
    $apiKey = "AIzaSyAwskhHCz7l-rest of browser key"; // Browser Key that was obtained from Google.....
  
    // Replace with real client registration IDs
    $registrationIDs = array( $row->id );
      
    // Set POST variables
    $url = 'https://android.googleapis.com/gcm/send';
  
    $fields = array(
                    'registration_ids'  => $registrationIDs,
                    'data'              => array( "data" => $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_SSL_VERIFYPEER, false);
    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);
}


I even installed FireFox with Firebug... so I could debug php and all. Unfortunately, it would REBOOT my XP (no blue screen of death or anything - simply pull the power plug). So I un-installed that monster... (Chrome needs a proper debugger).

I am starting to think a big spiked caterpillar is on the menu.... (not so hairy yet female)

Edit: looks to me the green sections in the code are meant to be replaced with other values?? That's probably a result of my copy / paste style of coding...
 
Last edited:
Upvote 0
yes... That´s the part who have to be changed...

in $registrationIDs can be one or more registrationIDs. comma separated list.
Each ID is one destination user

Code: Copy
 $fields = array(
                    'registration_ids'  => $registrationIDs,
                    'data'              => array( "data" => $message ),
                    );
 
    $headers = array(
                        'Authorization: key=' . $apiKey,
                        'Content-Type: application/json'
                    );

$apiKey is your Api key from google.
 
Last edited:
Upvote 0
YES!!!! Order me up a BIG can of insects!

After much fooling around, I got the function working! After searching for "how to enable curl on Ubuntu" -
I had to find "dynamic extensions" in my php.ini and add:

extension=curl.so

After that restart apache2 and check phpinfo() and curl was enabled (as it was not before)!


The ChromePhp::log() allows me to see php vars in the debug of Chrome...


Now to work out this issue:

I want to send the message (no problem) and WHO sent the message (the logged in user), in a separate field.
How do I structure the output to do that?


You were right! It´s not that hard to manage! ;-) Just takes some time!
Of course, if it wasn't for the wonderful code posted - I would not have a clue on how to accomplish this task...

Thank you and everyone so much!
(I just elevated my skills one notch above HACK!)


Code: Copy
function sendGCM($UserID, $message, $mysqli ) {
   
  if ($stmt = $mysqli->prepare("SELECT id FROM devices WHERE name = ?"))
  {
      $stmt->bind_param('s', $UserID);   
      $stmt->execute(); // Execute the prepared query.
      $stmt->store_result();
      $stmt->bind_result($myid);     
      $stmt->fetch();
      if($stmt->num_rows > 0){
          ChromePhp::log("Num Rows ".$stmt->num_rows);   
          ChromePhp::log("Reg ID ".$myid);   
         
      } else {
          ChromePhp::log("No Rows ".$stmt->num_rows);   
            } 
    }                   
    else {
          ChromePhp::log("Could not execute stmt ");   
   
    }
 
// $query = "SELECT id From devices Where name=$UserID";   // this wasn't working.....
//    $row = mysql_fetch_object(mysql_query($query));
// Replace with real BROWSER API key from Google APIs

    $apiKey = "AIzaSyAwskhHCz7l-my real browser key from Google"; // Browser Key
  ChromePhp::log("apikey ".$apiKey); 
   
    // Replace with real client registration IDs
    $registrationIDs = array( $myid );
  ChromePhp::log("User Name ".$UserID);
  ChromePhp::log("Message ".$message);
      
    // Set POST variables
    $url = "https://android.googleapis.com/gcm/send";
  ChromePhp::log("url ".$url);
   
    $fields = array(
                    'registration_ids'  => $registrationIDs,
                    'data'              => array( "data" => $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_SSL_VERIFYPEER, false);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
   
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
   
    // Execute post
    $result = curl_exec($ch);
    ChromePhp::log("result: ".$result); 

    // Close connection
    curl_close($ch);
}
 
Upvote 0
I want to send the message (no problem) and WHO sent the message (the logged in user), in a separate field.
How do I structure the output to do that?

Found the answer - This seems to work...

Code: Copy
$fields = array(
                    'registration_ids'  => $registrationIDs,
                    'data'              => array( "data" => $message, "sentby" => $sb ),
                    );

"sentby" => $sb - adds more params to the message content (who sent the message). Now in the B4A app:

Code: Copy
Sub MessageArrived (Intent As Intent)
    Dim From, CollapseKey, SentBy, Data As String 'ignore
    If Intent.HasExtra("sentby") Then
      SentBy = Intent.GetExtra("sentby") // add the logged in sender/user
    Else
      SentBy = "dispatch"  // or add the default "dispatch" sender
    End If 

    PushServiceCM.SQL1.ExecNonQuery2("INSERT INTO mess_in (time_in, from_user,mess_text,read_it) VALUES(?,?,?,?)", Array As Object(DateTime.Now,SentBy,Data,0))

Still amazed by how fast and reliable this is. Very nice...
 
Upvote 0
Back
Top