Monday, April 21, 2014

Google Cloud Messaging(GCM) for Android. (Part 2/2)

6. Implement GCM receiver code.(Client)
<< Broadcast Receiver class>>

public class GCMBroadcastReceiver extends WakefulBroadcastReceiver{
public static final String Key_Type = "Type";
public static final String Key_Command = "CMD";
public static final String Key_Msg = "MSG";

@Override
public void onReceive(Context context, Intent intent) {
    Log.i("GCMBroadcastReceiver.onReceive","new message is received.");


    Bundle extras = intent.getExtras();
    String action = intent.getAction();
    if(extras != null){
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
        String messageType = gcm.getMessageType(intent);
        // read data from gcm

        String type = intent.getStringExtra(Key_Type);
        String command = intent.getStringExtra(Key_Command);
        String msg = intent.getStringExtra(Key_Msg);

        // TODO you can add some specific code to do....
        // You can start new service to do some works.
        // startWakefulService(context, (intent.setComponent(comp)));
        // see the artical in google developer's guide http://developer.android.com/google/gcm/client.html#sample-receive

    }
}
}


7. Setup in AndroidManifast.xml file.(Client)
The instuction under ... http://developer.android.com/google/gcm/client.html#manifest

<manifest package="com.example.gcm" ...>
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" /> <!-- I didn't add this permission -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission android:name="com.example.gcm.permission.C2D_MESSAGE"

android:protectionLevel="signature" />

    <uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />


<application ...>
            <receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
                <intent-filter>
                    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                    <category android:name="com.example.gcm" />
                </intent-filter>
            </receiver>
            <service android:name=".GcmIntentService" /> <!-- if you created service to handle gcm messages you should add this service-->
</application>


8. Implement GCM message sender.(Server)
  • This is the PHP function to send gcm message to GCM connecton server.
  • You can also send gcm message to GCM connection server from you android app.
  • As you may not need it if you have a server to send the message, I will not add the codes. :-)
  • I used Curl... and you can use the lib with comment off this extesion in php.ini, if you installed latest WAMP server.
  • extension=php_curl.dll

function sendGCMMessage_($data, $registrationIDs)
{   $apiKey = 'GsfgaSFc13-2reIDSD4qK_3_dfghspVWDSxEAA'; // this is the brower key you generated in 3. Creating a Google API project and obtaining an API Key.

    $senderId = "153023456724"; // this is the project code you generated in 3. Creating a Google API project and obtaining an API Key.

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

 

   $fields = array(

   'delay_while_idle' => False, // If you want to receive message when the phone is idle, you have to set this 'False'. You can set this 'True' to save the battery.
   'time_to_live' => 108,
   'collapse_key' => 'score_update',
   'registration_ids' => $registrationIDs,
   'data' => $data,

   );

   $headers = array(

   'Authorization: key=' . $apiKey,
   'Sender: id=' . $senderId,
   '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));

   $result = curl_exec($ch);

   return $result;

}
  • how to call the function?? It is quite easy. 

$registrationIDs = array("APA91bEr6sdfjJzIsdfO76YsdfsvQ5NGago9JvRYod0v-n...", "APA91bEr6zWLWizsdfMO76YVRdfsfQ5NGagdfYod0vdsf...");
// The registeration id you obtained in 5. Implement GCM register code.(Client). You can add multiful registeration ids.

$data = array("Type" => "My Type", "CMD" => 'My Command', "MSG" => "My Message" );
// You should add the same key value pairs just the same as you will receive in you client app you implemented in 6. Implement GCM receiver code.(Client).
$result = sendGCMMessage_($data, $registrationIDs);
 

No comments:

Post a Comment