A Case Study of an Android* Client App Using Cloud-Based Alert Service

Similar documents
How To Develop Smart Android Notifications using Google Cloud Messaging Service

Intel Media SDK Library Distribution and Dispatching Process

Intel HTML5 Development Environment. Article - Native Application Facebook* Integration

Intel SSD 520 Series Specification Update

* * * Intel RealSense SDK Architecture

Intel Solid-State Drive Pro 2500 Series Opal* Compatibility Guide

Cloud Service Brokerage Case Study. Health Insurance Association Launches a Security and Integration Cloud Service Brokerage

Cloud based Holdfast Electronic Sports Game Platform

Intel Desktop Board D945GCPE

Intel Service Assurance Administrator. Product Overview

Intel Identity Protection Technology (IPT)

Intel Internet of Things (IoT) Developer Kit

Intel Core i5 processor 520E CPU Embedded Application Power Guideline Addendum January 2011

Intel Desktop Board DG41BI

Intel Desktop Board DG43RK

The Case for Rack Scale Architecture

Intel Desktop Board D945GCPE Specification Update

Intel Desktop Board DG41TY

Intel Desktop Board DG31PR

Intel Desktop Board DP55WB

with PKI Use Case Guide

Intel and Qihoo 360 Internet Portal Datacenter - Big Data Storage Optimization Case Study

Google Developer Group Perugia DevFest Central Rome

Mobile Push Architectures

Intel HTML5 Development Environment. Tutorial Test & Submit a Microsoft Windows Phone 8* App (BETA)

Intel Desktop Board DQ43AP

Intel Identity Protection Technology Enabling improved user-friendly strong authentication in VASCO's latest generation solutions

Intel Desktop Board DG41WV

Intel Desktop Board DQ35JO

Benchmarking Cloud Storage through a Standard Approach Wang, Yaguang Intel Corporation

iscsi Quick-Connect Guide for Red Hat Linux

Intel Desktop Board D945GCL

Intel HTML5 Development Environment. Tutorial Building an Apple ios* Application Binary

Intel HTML5 Development Environment Article Using the App Dev Center

Android and Cloud Computing

This guide explains how to install an Intel Solid-State Drive (Intel SSD) in a SATA-based desktop or notebook computer.

Intel Solid-State Drive Data Center Tool User Guide Version 1.1

Intel Media Server Studio - Metrics Monitor (v1.1.0) Reference Manual

Intel Desktop Board DG33TL

Intel Desktop Board DQ965GF

The ROI from Optimizing Software Performance with Intel Parallel Studio XE

GCM GOOGLE CLOUD MESSAGING

Resetting USB drive using Windows Diskpart command

Intelligent Business Operations

Intel Retail Client Manager Audience Analytics

Head-Coupled Perspective

COSBench: A benchmark Tool for Cloud Object Storage Services. Jiangang.Duan@intel.com

Accelerating Business Intelligence with Large-Scale System Memory

Intel Desktop Board DP43BF

Intel Cloud Builder Guide: Cloud Design and Deployment on Intel Platforms

Intel Platform and Big Data: Making big data work for you.

Intel Integrated Native Developer Experience (INDE): IDE Integration for Android*

Intel System Event Log (SEL) Viewer Utility

Version Rev. 1.0

Intel Desktop Board D101GGC Specification Update

System Event Log (SEL) Viewer User Guide

Three Paths to Faster Simulations Using ANSYS Mechanical 16.0 and Intel Architecture

Creating Overlay Networks Using Intel Ethernet Converged Network Adapters

Intel Platform Controller Hub EG20T

Intel Core TM i7-660ue, i7-620le/ue, i7-610e, i5-520e, i3-330e and Intel Celeron Processor P4505, U3405 Series

Salesforce Mobile Push Notifications Implementation Guide

Intel Core TM i3 Processor Series Embedded Application Power Guideline Addendum

Intel Desktop Board DG965RY

Fast, Low-Overhead Encryption for Apache Hadoop*

Intel Network Builders: Lanner and Intel Building the Best Network Security Platforms

Intel Small Business Advantage (Intel SBA) Release Notes for OEMs

Intel EP80579 Software for Security Applications on Intel QuickAssist Technology Cryptographic API Reference

System Image Recovery* Training Foils

Scaling Networking Solutions for IoT Challenges and Opportunities

Software Solutions for Multi-Display Setups

Power Benefits Using Intel Quick Sync Video H.264 Codec With Sorenson Squeeze

Intel Cloud Builders Guide to Cloud Design and Deployment on Intel Platforms

Intel Cyber Security Briefing: Trends, Solutions, and Opportunities. Matthew Rosenquist, Cyber Security Strategist, Intel Corp

Accelerating Business Intelligence with Large-Scale System Memory

How to Configure Intel X520 Ethernet Server Adapter Based Virtual Functions on Citrix* XenServer 6.0*

Intel Cloud Builder Guide to Cloud Design and Deployment on Intel Platforms

Maximize Performance and Scalability of RADIOSS* Structural Analysis Software on Intel Xeon Processor E7 v2 Family-Based Platforms

How To Reduce Pci Dss Scope

Intel Technical Advisory

Intel Media Server Studio Professional Edition for Windows* Server

Intel Data Direct I/O Technology (Intel DDIO): A Primer >

Intel Remote Configuration Certificate Utility Frequently Asked Questions

Enhancing McAfee Endpoint Encryption * Software With Intel AES-NI Hardware- Based Acceleration

Specification Update. January 2014

Intel Modular Server System MFSYS25

Intel Simple Network Management Protocol (SNMP) Subagent v6.0

Intel Network Builders

Advertiser Campaign SDK Your How-to Guide

Intel Ethernet and Configuring Single Root I/O Virtualization (SR-IOV) on Microsoft* Windows* Server 2012 Hyper-V. Technical Brief v1.

Intel Solid-State Drives Increase Productivity of Product Design and Simulation

Intel Desktop Board D945GCZ

Intel RAID RS25 Series Performance

User Experience Reference Design

How High Temperature Data Centers and Intel Technologies Decrease Operating Costs

Revision History. Revision Revision History Date

Intel Data Migration Software

SDN. WHITE PAPER Intel Ethernet Switch FM6000 Series - Software Defined Networking. Recep Ozdag Intel Corporation

Hetero Streams Library 1.0

Intel Retail Client Manager

Transcription:

A Case Study of an Android* Client App Using Cloud-Based Alert Service Abstract This article discusses a case study of an Android client app using a cloud-based web service. The project was built on the Google* Cloud Messaging (GCM) a free service by Google. It uses a thirdparty library, Android Asynchronous Http Client, to post callback-based HTTP requests. It exchanges messages with the app server using JSON strings. The google-gson library is used to parse the JSON strings. The client also consumes web services exposed by the app server through a RESTful API. Overview This case study focused on developing an Android client app for a cloud-based healthcare alert service. A doctor or a nurse would have this client app installed on an Android device. The hospital s central paging system sends short notification messages to the device. The notification plays an alert sound and shows up on the device s status bar. The user acknowledges or responds to the alert. The user could also browse all the outstanding alerts and the history. The use case was very generic; it could be easily applied to other industries. Google Cloud Messaging for Android Google Cloud Messaging for Android (GCM) is a free service by Google that allows you to send messages from your server to an Android device where your app is running (Figure 1). It also allows your server to receive upstream messages from the Android app. For more details on GCM, please go to http://developer.android.com/google/gcm/gcm.html. 1

Android* Client App Your App Server Google Connection Servers Figure 1 An Android* app exchanges data with the app server via GCM Android Asynchronous Http Client GCM provides connection servers for HTTP and XMPP. In this project, we used a third-party library, Android Asynchronous Http Client to send requests to the application server. The library is under Apache Version 2 license. It is a callback-based HTTP client, in which HTTP requests happen outside the UI thread. For detailed usages of this library, please go to http://loopj.com/android-async-http/. Data Exchange Formats JSON (JavaScript* Object Notation, http://www.json.org/) is a popular data-interchange format used between web services and clients. In our Android client app, we used google-gson to parse the JSON string received from the server. For more information on the google-gson library, please visit https://code.google.com/p/google-gson/. 2

Register with GCM and Application Server The first time your Android app uses the GCM service, it needs to register with GCM by calling the com.google.android.gcm.gcmregistrar method register(). In our Android client app, this was done in the oncreate() method of the start activity (Code Example 1). package com.intcmobile.medipaging; import com.google.android.gcm.gcmregistrar; import com.loopj.android.http.*; public class SplashActivity extends Activity { protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); registerdevicewithgcm(); /* * Register device with GCM in background AsyncTask<Void, Void, Void> mregistertask; void registerdevicewithgcm() { if ((SENDER_ID == null) && (SERVER_URL == null)) { return; gcmregistrationid = GCMRegistrar.getRegistrationId(this); if(gcmregistrationid.equals("")) { GCMRegistrar.register(this, SENDER_ID); else { if (!GCMRegistrar.isRegisteredOnServer(this)) { final Context context = this; mregistertask = new AsyncTask<Void, Void, Void>() { protected Void doinbackground(void... params) { boolean registered = Utilities.serverRegister(context, gcmregistrationid); if (!registered) { // Asynchronous registration task failed. Unregister this device with GCM GCMRegistrar.unregister(context); 3

; return null; protected void onpostexecute(void result) { mregistertask = null; Code Example 1 Register the device with the GCM service ** In Code Example 1, we first check if the device is registered with GCM. If not, we register it with the GCM server. Then we check if the device is registered on the app server, if not, we kick off an AsyncTask to register it in the background. Code Example 2 shows the definition of the Utilities class. 4

package com.intcmobile.medipaging; import static com.intcmobile.medipaging.utilities.device_name; import static com.intcmobile.medipaging.utilities.server_url; import static com.intcmobile.medipaging.utilities.tag; import com.google.android.gcm.gcmregistrar; public class Utilities { * Handle register/unregister call back from GCMIntentService * Register this account/device pair with the gcm server. * This function is normally called from the onregistered call back function in GCMIntentService * * @return whether the registration succeeded or not. static boolean serverregister(final Context context, final String regid) { String serverurl = SERVER_URL + "/login"; Map<String, String> params = new HashMap<String, String>(); params.put("username", Utilities.userName); params.put("password", Utilities.password); params.put("regid", regid); try { post(serverurl, params); GCMRegistrar.setRegisteredOnServer(context, true); return true; catch (IOException e) { return false; { * Unregister this account/device pair on the server. static void serverunrregister(final Context context, final String regid) String serverurl = SERVER_URL + "/logout"; Map<String, String> params = new HashMap<String, String>(); params.put("regid", regid); try { post(serverurl, params); GCMRegistrar.setRegisteredOnServer(context, false); catch (IOException e) { //handle exception 5

* Issue a GET request to the server * private static void get(string endpoint) throws IOException { URL url; try { url = new URL(endpoint); catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openconnection(); conn.setdooutput(true); conn.setusecaches(false); conn.setrequestmethod("get"); conn.setrequestproperty("content-type","text/html"); // post the request OutputStream out = conn.getoutputstream(); out.close(); // handle the response int status = conn.getresponsecode(); status); if (status!= 200) { throw new IOException("HTTP GET failed with error code " + finally { if (conn!= null) { conn.disconnect(); * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. private static void post(string endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); 6

catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); StringBuilder bodybuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entryset().iterator(); // constructs the POST body using the parameters while (iterator.hasnext()) { Entry<String, String> param = iterator.next(); bodybuilder.append(param.getkey()).append('=').append(param.getvalue()); if (iterator.hasnext()) { bodybuilder.append('&'); String body = bodybuilder.tostring(); byte[] bytes = body.getbytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openconnection(); conn.setdooutput(true); conn.setusecaches(false); conn.setfixedlengthstreamingmode(bytes.length); conn.setrequestmethod("post"); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded;charset=utf-8"); // post the request OutputStream out = conn.getoutputstream(); out.write(bytes); out.close(); // handle the response int status = conn.getresponsecode(); if (status!= 200) { throw new IOException("HTTP POST operation failed with error code " + status); finally { if (conn!= null) { conn.disconnect(); Code Example 2 Utility methods used to register and unregister the device to the service running on the third-party app server ** 7

Receiving Push Notifications and Sending Confirmations In this project, we used a service called GCMIntentService to handle GCM push notifications. The service was derived from com.google.android.gcm.gcmbaseintentservice. When the Android client application received a message pushed by the app server, the GCMIntentService class s onmessage(context context, Intent intent) method was called, no matter if the app is currently active or not. 8

package com.intcmobile.medipaging; import com.google.android.gcm.gcmbaseintentservice; import com.google.android.gcm.gcmregistrar; import com.google.gson.gson; import com.google.gson.gsonbuilder; public class GCMIntentService extends GCMBaseIntentService { public GCMIntentService () { super(sender_id); protected void onerror(context context, String errormessage) { displaymessage(context, "There were error receiving notification. Error message: " + errormessage); protected void onmessage(context context, Intent intent) { String alerttype = intent.getstringextra("alerttype"); String alertid = intent.getstringextra("alertid"); String alertsubject = intent.getstringextra("subject"); SimpleAlertInfo alert = new SimpleAlertInfo(alertType, alertid, alertsubject); alerts.add(alert); displaymessage(context,alert.tostring()); protected void onregistered(context context, String registrationid) { // This method is called when the application successfully register with GCM service // register with 3 rd party app server Utilities.serverRegister(context, registrationid); { protected void onunregistered(context context, String registrationid) if (GCMRegistrar.isRegisteredOnServer(context)) { Utilities.serverUnregister(context, registrationid); Code Example 3 The GCMIntentService class handles the server push notifications ** We added the GCMIntentService in the app s AndroidManifest.xml file as shown in Code Example 4. 9

<!-- Broadcast receiver that will receive intents from GCM service and hands them to the custom IntentService --> <receiver android:name="com.google.android.gcm.gcmbroadcastreceiver" android:permission="com.google.android.c2dm.permission.send" > <intent-filter> <!-- receives the actual GCM message --> <action android:name="com.google.android.c2dm.intent.receive" /> <!-- receives the registration ID --> <action android:name="com.google.android.c2dm.intent.registration" /> <!-- category --> <category android:name="com.intcmobile.medipaging" /> </intent-filter> </receiver> <!-- Application specific subclass of GCMIntentService that will handle received message --> <service android:name="com.intcmobile.medipaging.gcmintentservice" /> Code Example 4 Define the GCMIntentService in the Android* client app's AndroidManifest.xml file ** Consuming RESTful Services Besides receiving pushed alert notifications from the app server, the Android client app also consumes cloud-based web services exposed by the app server API via a REST interface. The basic mechanism for doing this is the Android client app posting an asynchronous HTTP request to the server. If successful, the app server returns a JSON string back to the client app (Code Example 5). 10

package com.intcmobile.medipaging; import com.google.gson.gson; import com.google.gson.gsonbuilder; import com.loopj.android.http.asynchttpclient; import com.loopj.android.http.asynchttpresponsehandler; import com.loopj.android.http.requestparams; public class DisplayAlertsActivity extends Activity { public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_display_alerts); fetchdataforhomescreen(); private void fetchdataforhomescreen () { AsyncHttpClient client = new AsyncHttpClient(); StdRequestParams parameters = new StdRequestParams(); String url = SERVER_URL + "/getdataforhomescreen"; showprogress(true); client.post(url, parameters, new AsyncHttpResponseHandler() { public void onsuccess(string response) { jsondataforhomescreen = response; Gson gson_obj = new GsonBuilder().setPrettyPrinting().create(); medipagingdataforhomescreen = gson_obj.fromjson(jsondataforhomescreen, GetDataResp.class); ); ishomescreendataavailable = true; showprogress(false); displayalerts(); public void onfailure(throwable e, String response) { // Response failed :( showprogress(false); public void onfinish() { showprogress(false); 11

Code Example 5 The Android* client app consumed RESTful web service using the Android Asynchronous Http Client ** In Code Example 5, we can see the Android client app uses Android Asynchronous Http client to post an HTTP request to the app server. This happens outside of the UI thread so that the Android app could still be responsive to user input. We also see, if successful, a JSON string is returned from the app server. The Android client app uses google-gson to parse the JSON string and create a GetDataResp object. Code Example 6 shows the definition of the GetDataResp class. package com.intcmobile.common; import java.util.*; * The return from Get Data as well as a bunch of the other calls. public class GetDataResp extends BaseReturn { Outstanding alerts. public ArrayList<AlertInfo> alerttable; * Constructor. public GetDataResp() { * Constructor. public GetDataResp(int _returncode, String _reason) { super(_returncode, _reason); Code Example 6 GetDataResp class definition ** Summary In this article, we have discussed a case study of how to use Google Cloud Messaging to create an Android cloud-based alert service client app. In this project, we used a third-party asynchronous HTTP client to achieve the non-blocking UI. We also used JSON as the data exchange format between the app server and the Android client. From this case study, we can see a cloud service Android client app is very easy to implement. The approach discussed in this article can be applied in other cloud-based service client applications. 12

About the Author Miao Wei is a software engineer in the Intel Software and Services Group. He currently works on the Intel Atom processor scale enabling projects. Notices INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT. UNLESS OTHERWISE AGREED IN WRITING BY INTEL, THE INTEL PRODUCTS ARE NOT DESIGNED NOR INTENDED FOR ANY APPLICATION IN WHICH THE FAILURE OF THE INTEL PRODUCT COULD CREATE A SITUATION WHERE PERSONAL INJURY OR DEATH MAY OCCUR. Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined." Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information. The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request. Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order. Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-4725, or go to: http://www.intel.com/design/literature.htm Software and workloads used in performance tests may have been optimized for performance only on Intel microprocessors. Performance tests, such as SYSmark* and MobileMark*, are measured using specific 13

computer systems, components, software, operations, and functions. Any change to any of those factors may cause the results to vary. You should consult other information and performance tests to assist you in fully evaluating your contemplated purchases, including the performance of that product when combined with other products. Any software source code reprinted in this document is furnished under a software license and may only be used or copied in accordance with the terms of that license. Intel, the Intel logo, and Atom are trademarks of Intel Corporation in the U.S. and/or other countries. Copyright 2013 Intel Corporation. All rights reserved. *Other names and brands may be claimed as the property of others. **This sample source code is released under the Intel Sample Source Code License Agreement (http://software.intel.com/en-us/articles/intel-sample-source-code-license-agreement/) 14