Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Google Cloud Messaging in Action !

Google Cloud Messaging in Action !

Devoxx Antwerp 2013

Thomas Guerin

November 11, 2013
Tweet

More Decks by Thomas Guerin

Other Decks in Programming

Transcript

  1. @Tom404_ #DV13-gcm Google Cloud Messaging • Push message service •

    No more client polling • Messages are queued while device is offline
  2. @Tom404_ #DV13-gcm Google Cloud Messaging • Push message service •

    No more client polling • Messages are queued while device is offline • Two types of messages • send-to-sync • with payload
  3. @Tom404_ #DV13-gcm Message with payload • Non-collapsible message • Up

    to 4 kb of payload data • Delivery order not guaranteed
  4. @Tom404_ #DV13-gcm Message with payload • Non-collapsible message • Up

    to 4 kb of payload data • Delivery order not guaranteed • Max 100 non-collapsible messages per queue
  5. @Tom404_ #DV13-gcm Main advantages • Reduces update latency ! •

    Preserves battery life ! • Part of Google Play Services ! • Available back to Android 2.2
  6. @Tom404_ #DV13-gcm Main advantages • No quota limits ! •

    Unicast/multicast ! • App doesn’t need to be running to receive messages
  7. @Tom404_ #DV13-gcm Data flow 1 3 2 a Server Mobile

    Registration flow Message flow
  8. @Tom404_ #DV13-gcm Data flow 1 3 2 a b Server

    Mobile Registration flow Message flow
  9. @Tom404_ #DV13-gcm Prerequisites • Google account • Create a project

    in https://cloud.google.com/console • Project number
  10. @Tom404_ #DV13-gcm Prerequisites • Google account • Create a project

    in https://cloud.google.com/console • Project number • Server API key
  11. @Tom404_ #DV13-gcm Simple as a POST • POST request to

    https://android.googleapis.com/gcm/send
  12. @Tom404_ #DV13-gcm Simple as a POST • POST request to

    https://android.googleapis.com/gcm/send • Two headers required • Content-Type • Authorization
  13. @Tom404_ #DV13-gcm Simple as a POST • POST request to

    https://android.googleapis.com/gcm/send • Two headers required • Content-Type • Authorization • Specific format
  14. @Tom404_ #DV13-gcm {   ! ! ! ! ! !

    ! ! ! }   Message format "collapse_key":  "your_collapse_key", "time_to_live":  108, "delay_while_idle":  true, "data":  {     "message":  "Hi  from  GCM!"   }, "registration_ids":  ["1",  "2"] "restricted_package_name":  "com.devoxx.gcm"  , "dry_run":  false,
  15. @Tom404_ #DV13-gcm {   ! ! ! ! ! !

    ! ! ! }   Message format "collapse_key":  "your_collapse_key", "time_to_live" "delay_while_idle" "data"   }, "registration_ids" "restricted_package_name" "dry_run"
  16. @Tom404_ #DV13-gcm {   ! ! ! ! ! !

    ! ! ! }   Message format "collapse_key" "time_to_live":  108, "delay_while_idle" "data"   }, "registration_ids" "restricted_package_name" "dry_run"
  17. @Tom404_ #DV13-gcm {   ! ! ! ! ! !

    ! ! ! }   Message format "collapse_key" "time_to_live" "delay_while_idle":  true, "data"   }, "registration_ids" "restricted_package_name" "dry_run"
  18. @Tom404_ #DV13-gcm {   ! ! ! ! ! !

    ! ! ! }   Message format "collapse_key" "time_to_live" "delay_while_idle" "data":  {     "message":  "Hi  from  GCM!"   }, "registration_ids" "restricted_package_name" "dry_run"
  19. @Tom404_ #DV13-gcm {   ! ! ! ! ! !

    ! ! ! }   Message format "collapse_key" "time_to_live" "delay_while_idle" "data"   }, "registration_ids" "restricted_package_name":  "com.devoxx.gcm"  , "dry_run"
  20. @Tom404_ #DV13-gcm {   ! ! ! ! ! !

    ! ! ! }   Message format "collapse_key" "time_to_live" "delay_while_idle" "data"   }, "registration_ids" "restricted_package_name" "dry_run":  false,
  21. @Tom404_ #DV13-gcm {   ! ! ! ! ! !

    ! ! ! }   Message format "collapse_key" "time_to_live" "delay_while_idle" "data"   }, "registration_ids":  ["1",  "2"] "restricted_package_name" "dry_run"
  22. @Tom404_ #DV13-gcm var  request  =  require('request');   ! ...  

    ! request(          {      method:  'POST',                  uri:"https://android.googleapis.com/gcm/send",                  headers:{'Content-­‐type':  'application/json',  'Authorization':  'key=YOUR_KEY'},                  json:{                          'registration_ids':  ['1',  '2',  '3',  '4',  '5',  '6'],                          'collapse_key':  'Update  now'                  }          },function(err,res,gcmResult){                  //  Handle  the  result          }   ) Sample request
  23. @Tom404_ #DV13-gcm {        "multicast_id":  216,    

     "success":  3,      "failure":  3,      "canonical_ids":  1,      "results":  [          {  "message_id":  "1:0408"  },          {  "error":  "Unavailable"  },          {  "error":  "InvalidRegistration"  },          {  "message_id":  "1:1516"  },          {  "message_id":  "1:2342",  "registration_id":  "32"  },          {  "error":  "NotRegistered"}      ]   }   Response format
  24. @Tom404_ #DV13-gcm   Permissions <uses-­‐permission  android:name="android.permission.INTERNET"  /> <uses-­‐permission  android:name="android.permission.GET_ACCOUNTS"  />

    <uses-­‐permission  android:name="android.permission.WAKE_LOCK"  /> <uses-­‐permission  android:name="com.google.android.c2dm.permission.RECEIVE"  />
  25. @Tom404_ #DV13-gcm   Permissions <uses-­‐permission  android:name="android.permission.INTERNET"  /> <uses-­‐permission  android:name="android.permission.GET_ACCOUNTS"  />

    <uses-­‐permission  android:name="android.permission.WAKE_LOCK"  /> <uses-­‐permission  android:name="com.google.android.c2dm.permission.RECEIVE"  /> <permission          android:name="com.devoxx.gcm.permission.C2D_MESSAGE"          android:protectionLevel="signature"  />   <uses-­‐permission  android:name="com.devoxx.gcm.permission.C2D_MESSAGE"  />
  26. @Tom404_ #DV13-gcm private  boolean  checkPlayServices()  {        

     int  resultCode  =  GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);                    if  (resultCode  !=  ConnectionResult.SUCCESS)  {                  if  (GooglePlayServicesUtil.isUserRecoverableError(resultCode))  {                          GooglePlayServicesUtil.getErrorDialog(resultCode,  this,                                          PLAY_SERVICES_RESOLUTION_REQUEST).show();                  }  else  {                          Log.i(TAG,  "This  device  is  not  supported.");                          finish();                  }                  return  false;          }          return  true;   }   Play services, are you there?
  27. @Tom404_ #DV13-gcm ! ! ! ! ! Registration try  {

              ! ! ! ! ! ! }  catch  (IOException  e)  {          Log.i(TAG,  "Registration  failed");   }          GoogleCloudMessaging  gcm  =  GoogleCloudMessaging.getInstance(context); String  registrationId  =  gcm.register(getString(R.string.sender_id));        if  (sendRegistrationIdToServer(registrationId))  {                          } storeRegistrationId(context,  registrationId);
  28. @Tom404_ #DV13-gcm ! ! ! ! ! Registration try  

          ! ! ! ! ! ! }           }          GoogleCloudMessaging  gcm  =  GoogleCloudMessaging.getInstance(context); String  registrationId  =  gcm.                                } storeRegistrationId
  29. @Tom404_ #DV13-gcm ! ! ! ! ! Registration try  {

              ! ! ! ! ! ! }  catch  (IOException  e)  {          Log.i(TAG,  "Registration  failed");   }          GoogleCloudMessaging  gcm  =  GoogleCloudMessaging. String  registrationId  =  gcm.register(getString(R.string.sender_id));                                } storeRegistrationId
  30. @Tom404_ #DV13-gcm ! ! ! ! ! Registration try  

          ! ! ! ! ! ! }           }          GoogleCloudMessaging  gcm  =  GoogleCloudMessaging. String  registrationId  =  gcm.        if  (sendRegistrationIdToServer(registrationId))  {                          } storeRegistrationId
  31. @Tom404_ #DV13-gcm ! ! ! ! ! Registration try  

          ! ! ! ! ! ! }           }          GoogleCloudMessaging  gcm  =  GoogleCloudMessaging. String  registrationId  =  gcm.                                } storeRegistrationId(context,  registrationId);
  32. @Tom404_ #DV13-gcm public  class  GcmBroadcastReceiver  extends  WakefulBroadcastReceiver  {   !

           @Override          public  void  onReceive(Context  context,  Intent  intent)  {                  ComponentName  comp  =  new  ComponentName(context.getPackageName(),                                  GcmMessageHandlerIntentService.class.getName());                                    startWakefulService(context,  intent.setComponent(comp));                                    setResultCode(Activity.RESULT_OK);          }   ! }   Message reception
  33. @Tom404_ #DV13-gcm ! ! Message reception @Override   protected  void

     onHandleIntent(Intent  intent)  {           ! ! ! ! ! ! ! ! ! ! ! ! ! }        Bundle  extras  =  intent.getExtras();          if  (!extras.isEmpty())  {                     ! ! ! ! ! ! ! ! !      }  GoogleCloudMessaging  gcm  =  GoogleCloudMessaging.getInstance(this);                String  messageType  =  gcm.getMessageType(intent);                  if  (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType))  {   !                }  else  if  (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType))  {   !                }  else  if  (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType))  {                    String  message  =  intent.getStringExtra("message");                  } GcmBroadcastReceiver.completeWakefulIntent(intent);
  34. @Tom404_ #DV13-gcm ! ! Message reception @Override protected    

      ! ! ! ! ! ! ! ! ! ! ! ! ! }        Bundle  extras  =  intent.getExtras();          if  (!extras.isEmpty())  {                     ! ! ! ! ! ! ! ! !      }  GoogleCloudMessaging  gcm  =  GoogleCloudMessaging.getInstance(this);                String  messageType  =  gcm.                 !                }   !                }                    String  message  =  intent.                } GcmBroadcastReceiver.
  35. @Tom404_ #DV13-gcm ! ! Message reception @Override protected    

      ! ! ! ! ! ! ! ! ! ! ! ! ! }        Bundle  extras  =  intent.                         ! ! ! ! ! ! ! ! !      }  GoogleCloudMessaging  gcm  =  GoogleCloudMessaging.                String  messageType  =  gcm.getMessageType(intent);                  if  (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType))  {   !                }  else  if  (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType))  {   !                }  else  if  (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType))  {                    String  message  =  intent.getStringExtra("message");                  } GcmBroadcastReceiver.
  36. @Tom404_ #DV13-gcm ! ! Message reception @Override protected    

      ! ! ! ! ! ! ! ! ! ! ! ! ! }        Bundle  extras  =  intent.                         ! ! ! ! ! ! ! ! !      }  GoogleCloudMessaging  gcm  =  GoogleCloudMessaging.                String  messageType  =  gcm.                 !                }   !                }                    String  message  =  intent.                } GcmBroadcastReceiver.completeWakefulIntent(intent);
  37. @Tom404_ #DV13-gcm What’s new? • GCM HTTP • Upstream (GCM

    Cloud Connection Server) • User notifications