Android Integration Perry Hoekstra Technical Consultant perry.hoekstra@perficient.com.

Post on 20-Dec-2015

221 views 5 download

Tags:

Transcript of Android Integration Perry Hoekstra Technical Consultant perry.hoekstra@perficient.com.

Android Integration

Perry HoekstraTechnical Consultantperry.hoekstra@perficient.com

There is an App for That

Gartner says …

Smartphones in the US

Two Horse Race?

Consumers

Smartphones (and possibly tablets) are fast overtaking conventional computers as the life-management workstation of choice for consumers

Consumers

The vision is that literally a billion people getting inexpensive, browser-based touchscreen phones over the next few years in developing countries.

Inquiring minds want to know …

Corporate clients (and internal IT departments) are not asking for slingshotted birds at evil green pigs …

What are corporations looking for?

Not witty responses to office trash talk …

Or beer tracking applications …

So what is on the minds of CTOs?

• How can we tie mobile computing to our current client-facing Internet offerings into a comprehensive mobile/Internet strategy?

• How do we support our own mobile workforce?

Consumer Mobile Strategy

• Financial institutions have been in the vanguard

• Previously, had invested heavily in SOA architectures

• Made their secure web sites available in mobile-friendly formats

• Rolled out selective native applications

Bring your own Device (BYOD)

• John CEO gets a new iPad from his wife for Xmas

• Likes it and would like to:– read corporate

email from it– view corporate

reports from reports server

• What do you say?

Expanding the Corporate Network

• Smartphones and tablets are the new corporate perimeter– Phones are always with

the business user– Tablets fit in an 8x11

leather portfolio and will eliminate the netbook market

• Surveys indicate that by 2015, mobile development will eclipse traditional enterprise development as an IT professional focus

Workplace 2.0

• Need to consider an enterprise mobility strategy

• SOA is an ideal enabler for sophisticated mobile web applications

• Mobile devices are typically on the move outside their office and homes

Reason for “Android Integration”

Enterprise mobile development generally means developing a distributed application (the device accessing one or more servers)

Professional Development

If you as a developer are looking to get into the mobile space: • Consumer app that supports current corporate end

users• Support internal users with tasks such as filling out

expense reports • Each is a distributed application

Mobile as an SOA Platform

• Android currently supports SOA-enabled apps such as Gmail, Google Calendar & Contacts.

• Each have separate UIs but share common data

• Other SOA-enabled apps running on mobile devices include Twitter and Facebook

Business Apps

• Other than the popular Google apps, most of the major mobile business apps are not SOA-enabled

• Rather, they boost the productivity and ease-of-use such as Swype

• Google launched Google Apps Marketplace to the business-oriented consumer

SOA-enabled Mobile Apps

• However, apps like the ones from Walgreens are.

• Using the unique capabilities of a mobile device:– Capture the prescription’s

bar code through camera phone and send in

– Check on current RXs– Locate pharmacy

• Tied to current backend Walgreen web services

Internal SOA-enabled Mobile Apps

• Field force automation – Especially those using

dedicated devices– Work order, status tracking– Product manuals

• Sales personnel– Sales and product data– Product availability– Order status

• Enterprise data– ERP and CRM

Not your Father’s SOA

• Mobile platforms have their own set of challenges in running within an SOA given:

– Bandwidth– Memory and CPU Availability– Connectivity Issues– Storage Capacity– Security

Bandwidth

• As a developer, when you implemented a web service, you assumed:– Had a reliable connection– Had a fat pipe – The other end had significant processing

power

• Therefore, the requests and replies could be very large and complex and require a lot of processing and parsing.

• But none of these assumptions hold true with a cell phone over a cell phone network

Processing Service Messages

• Decreasing returns for XML with large data sets and repetitive XML sections

• Processing power and memory limited to parse large XML datasets

• Minimize large data sets:– Ask for only those elements that you

require– Store what you can locally instead of

requesting the same data

• Possibly move to JSON to decrease size of data message

Spring Mobile & Spring Android

• Spring Android is focused on their RestTemplate library for interaction with back-end services

• Will be their platform going forward for a Java-based framework

• Spring Mobile also has their RestTemplate library but also code for server-side interaction with mobile devices

• Embeds with Spring MVC to detect mobile devices and redirect them to a m.*.* mobile-optimized web site

Go to code …

Significant Code Points

Some points about the code, depends on:– Spring Android framework– Spring Http Client (Apache Http Client)– Jackson REST framework

Have a full, working example called Greenhouse– Not much in way of integration examples (other

than RestClient)

Significant Code Points

Two major methods to make a REST call:– getObject– exchange

The big difference in which method to use is that exchange allows the developer to manipulate the HTTP headers

Significant Code Points

Either case, the JSON response is manifested to an object

ResponseEntity responseEntity = restTemplate.exchange(serverURL, HttpMethod.GET, new HttpEntity<String>(headers), RetrievalResponse.class);

RetrievalResponse retrievalResponse = (RetrievalResponse) responseEntity.getBody();

SOAP

• No SOAP embedded in base Android distribution

• There is a SOAP distribution called kSOAP2 used by a number of developers

• Not much enthusiasm with Google or development community

• Support existing services (lots of corporate SOAP/WSDL)

Memory & CPU

• The current generation of phones are constrained in terms of processing by the power of their CPU and memory

• In 2011, smartphones will be debuting with next-generate dual-core processors and Nvidia GeForce graphics core:– Play 1080p HD video– Videoconferencing

Future Horsepower

• By 2012, quad-core chips should be readily available

• Along with the CPU, graphics processing (NVIDIA) will also see a boost

• Both ARM (Cortex) and Intel (Medfield) are quickly following

Semi-Connected

• Developer assumed that PCs/laptops have wired Ethernet or reliable Wi-Fi built into the them

• Smartphones access the Internet via mobile connections (3G or Wi-Fi)

• These connections must be considered unreliable

• Want the app light and speedy on a standard 3G network

• May need to cache and maintain user session state on the phone so that can restore application state once Internet connection restored

Local Storage & Caching

• Cache locally in order to: – minimize service API round trips – preserve application session state

between connections

• Caching options– Cache in memory– Cache in onboard light weight

database or file– Off device persistence (SD card)

• Take into account when caching:– Length of time stored– Length of time before refresh

Go to code …

SQLite

public class OfflineDatabaseHelper extends SQLiteOpenHelper { private static int VERSION = 1; public static String DATABASE_NAME = "BeerDB"; public OfflineDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, VERSION); }

@Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE beers " + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "classification TEXT, name TEXT, description TEXT, " + "ratings TEXT)"); }

@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS beers");

onCreate(db); }

public void truncate(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS beers");

onCreate(db); }}

JDBC taste …

public class ResourceSQL { private OfflineDatabaseHelper db; public ResourceSQL(Context context) { db = new OfflineDatabaseHelper(context); }

public ArrayList<Beer> selectByClassification(String classification) { ArrayList<Beer> list = new ArrayList<Beer>(); SQLiteDatabase readableDB = db.getReadableDatabase();

String [] columns=new String[] {"_id", "classification", "name", "description", "rating"};

Cursor cursor = readableDB.query("resource", columns, "classification=?", new String[]{classification}, null, null, null);

if (cursor.moveToFirst()) { do { list.add(new Beer(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4))); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } return list; }}

What ORMLite provides

• OrmLiteSqliteOpenHelper – Extends SQLiteOpenHelper– Ormlite-specific onCreate and onUpgrade methods– Define some simple interactions for getting DAOs

• Base Activity and Service classes that manage DB opens/closes, etc.

• This is not your father’s Hibernate

ORMLite

@DatabaseTablepublic class Beer { @DatabaseField(generatedId = true)    private Integer beerId;    @DatabaseField private String classification;    @DatabaseField private String name;    @DatabaseField private String desc;    @DatabaseField private String rating; public Integer getBeerId() { return beerId; } public String getClassification() { return classification; } public void setClassification(String classification) { this.classification = classification; }

….}

Basic DAO

public class OfflineDatabaseHelper extends OrmLiteSqliteOpenHelper {

public Dao<Beer, Integer> getBeerao() throws SQLException { if (beerDao == null) { beerDao = BaseDaoImpl.createDao(databaseType, getConnectionSource(), Beer.class); }

return beerDao; }}

Data Synchronization

• If app is informational, needs to work whether connected or not

• If only works when connection, won’t get used

• Keep data current against backend changes

• Resynchronization upon reconnection

SQL

• Simplest approach is:- Server-to-mobile (full table update), depends on size- Mobile-to-server (incremental update)- Any table that need to sync up will contain a timestamp

column containing the date/time when the record was last touched (where updated_ts >= @last_sync_pt)

- Alternative is some type of version number (eliminate clock skew between mobile and DB server)

SQL

• A number of the SQL and NoSQL databases advertise seamless data synchronization for mobile including:

- Couchbase- Oracle Database Lite 10g

Push

• Synchronization solutions can either rely on the device polling or on some form of a push solution

• Polling– Balance between low

interval (drains battery) and higher interval (miss alerts)

– Does not hold connection open

Approaches

Approaches

• SMS– Good integration with Android – Limited payload

• Sockets– Persist connection including

keep-alives– Android could kill connection in

certain situations– Servers have this tendency too

Approaches

Message Queues

• Android Cloud to Device Messaging (C2DM)– Size limit 1024 bytes– Google throttles messages

sent/received• MQTT – IBM– Very attractive– Open protocol– No support on iOS

Go to code …

MQTT

• Did not want to install MQ, using IBM’s Real Small Message Broker (alphaWorks)

• Drop wmqtt.jar in the assets library

Security

• Along with caching, a smartphone can now act as a data repository for sensitive corporate data

• Some issues:– What are the risks to loss

and compromise?– What security controls are

available?– What new infrastructure

support is necessary?– Impact on web service calls?

• Mobile development generally means– A distributed system (the device accessing one or

more servers)– The device can easily be lost or stolen

• In both of these cases, one needs to pay particular attention to security, both on the wire and internally stored data

Basic Security

• HTTPS with Basic Auth will cover most developer needs. – However, if like most, I have self-signed certs.– Android has limited list of CA’s that it trusts by

default, a self-signed cert is not one of them.– Can alter code to accept all certs, but you don’t

want that to production.• All the advantages/disadvantages of what you

have now.

Go to code …

Basic Auth and SSLpublic String authenticate(SharedPreferences settings, String[] credentials) throws RestClientException { HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); RestTemplate restTemplate = new RestTemplate(requestFactory); HttpHeaders headers = new HttpHeaders();

try { String auth = android.util.Base64.encodeToString(((credentials[0] + ":" + credentials[1]).getBytes("UTF-8")), Base64.NO_WRAP);

headers.set("Authorization", "Basic " + auth); } catch (UnsupportedEncodingException unsupportedEncodingException) { Log.i(TAG, "Result: [" + unsupportedEncodingException.getMessage() + "]"); }

try { String fullpath = "https://" + ApplicationPreferences.getServerUrl(settings) + "/presentation/authenticate";

ResponseEntity responseEntity = restTemplate.exchange(fullpath, HttpMethod.GET, new HttpEntity<String>(headers), null);

// save the token for subsequent REST calls. return responseEntity.getHeaders().getFirst("Set-Cookie"); } catch (RestClientException restClientException) { Log.e(TAG, restClientException.getMessage()); throw restClientException; }}

Bit of a hack …

HttpHeaders headers = new HttpHeaders();

String cookie = ApplicationPreferences.getAuthCookie();

headers.set("Cookie", cookie);

ResponseEntity responseEntity = restTemplate.exchange(serverURL, HttpMethod.GET, new HttpEntity<String>(headers), RetrievalResponse.class);

OAuth

• Available within Android• Right approach for enterprise

security?– Pro: Want to move away from

userid/password– Con: Relying on third-party for

security (allowing another site to authenticate on behalf of the user)

• What about signatures?– REST-specific

Device Key

• There is the concept of a unique device key:– IMEI on GSM– MEID for CDMA

• Android has ANDROID_ID:– Android.Provider.S

ettings.System

Wrapup

• Balance flexibility with overhead in calls:– Greater filtering of criteria and paging of data functionality– Split out high traffic calls versus critical requests

• Optimize web service invocations to:– Decreased round trips– Increased efficiency of calls and applications– Better use of call volume restrictions

• Want to provide a rich user experience that is light and speedy on a standard 3G network

• May cause a restructuring of existing web services– Move to REST over WS-*

Just when you thought it was safe …

Next set of challenges:• Near-field

communications (NFC)• Simpler mechanisms to

bootstrap identity and credentials

• Better enterprise management and integration

Shameless promotional slide

Mobile User Experience

User Experience Blog:

http://productexperience.blogspot.com

“Best Practices in Mobile Web Design”

http://www.perficient.com/whitepapers

Mobile Web Design Presentation:

http://prezi.com/uptv_ijpwcv2/mobile-web-design-considerations/

Enterprise Mobile

I blog at: http://blogs.perficient.com/spark

Questions ?