208
Mobile Development A primer Giuseppe Sollazzo National Audit Office 25/7/2014

Mobile Development. A primer

Embed Size (px)

DESCRIPTION

Slides from my mobile development workshop at the National Audit Office. The workshop covered: - the history of mobile development - concepts of mobile development in iOS, Windows 8.1 Mobile, Android - practical exercises and examples

Citation preview

Page 1: Mobile Development. A primer

Mobile Development A primer

Giuseppe SollazzoNational Audit Office

25/7/2014

Page 2: Mobile Development. A primer

#0The obligatory intro

Page 3: Mobile Development. A primer

Goals

● Understanding mobile development● Exploring alternative technologies● Brainstorming apps● Get some first-hand experience

Page 4: Mobile Development. A primer

Outline

AM● A quick history of mobile development● Concepts of modern development● Simple code examples

PM● Practical exercises

Page 5: Mobile Development. A primer

Me

● Senior Systems Analyst at St George’s, University of London

● Freelance Developer● Open Data & Government Geek

Page 6: Mobile Development. A primer

#1The Mobile Scenario

Page 7: Mobile Development. A primer

#1.1A lifetime of mobile development

Page 8: Mobile Development. A primer

2006: my first app

Page 9: Mobile Development. A primer

2012: on the press

Page 10: Mobile Development. A primer

Sony Ericsson P990i

Symbian OS 9.1 - UIQ 3

ARM9 208MHz

RAM 64MB (OS: 48MB, User: 16MB)

Resolution 240x320

Java Micro Edition

iPhone 4

iOS

ARM Cortex ~1GHz

RAM 512MB

Resolution 960x640

Objective-C / Cocoa

Page 11: Mobile Development. A primer

29 June 2007 Image CC BY-NC-SA 2.0 by Stijn Vogels https://www.flickr.

com/photos/stijnvogels/351867946/

Page 12: Mobile Development. A primer

But it started much earlier!

● 1G phones have been out since the 80s○ lack of apps capabilities

● 2G phones (GSM) reach critical mass in early 90s○ dominated by Nokia○ limited features and memory○ small monochromatic screen○ pre-installed games

■ no easy way to install extra apps

Page 13: Mobile Development. A primer

Snake!(1998)

Image CC BY-NC-SA 2.0 by Utku Kalı https://www.flickr.com/photos/utku/6799941621

Page 14: Mobile Development. A primer

WAP(1997)

Image CC BY-NC 2.0 by Esko Kurvinen https://www.flickr.com/photos/ekurvine/853687173

Page 15: Mobile Development. A primer

WAP

● Protocol suite for data transfer on wireless devices ● Wap PUSH● Wireless Markup Language

<?xml version="1.0"?><!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"

"http://www.wapforum.org/DTD/wml_1.1.xml" >

<wml> <card id="main" title="First Card"> <p mode="wrap">This is a sample WML page. </p> </card></wml>

Page 16: Mobile Development. A primer

WAP

● Deck = WML document ● Deck structured in cards (=pages)● Wap 2.0 (2002): cut-down version of XHTML/HTTP

Page 17: Mobile Development. A primer

But it didn’t work

● Hard to type URL with numeric keypad● Limited screen -> limited applications● Extremely slow connections● Users accustomed to full web pages● No authoring tools, no content providers

Page 18: Mobile Development. A primer

i-Mode (1999)

● Created by DoCoMo, paid-for service● Similar to WAP but

○ C-HTML on HTTP clone○ 12K official sites (supervised by DoCoMo)○ 100K unofficial sites○ 80M subscribers

● Licensed in the UK by O2, it never took off

Page 19: Mobile Development. A primer

BlackBerry

● BB 850: 2-way pager launched in Munich (1999)● Focus on e-mail● Evolution in 2003 with convergent services

○ push email, telephone, SMS, …● Inconsistent developer support

○ Java SDK for BlackBerry OS 7○ Today: BB 10, BB PlayBook, BB OS

Page 20: Mobile Development. A primer

Psion Revo (1999)Image CC BY-NC 2.0 by Modrak https://www.flickr.com/photos/modrak/239348772

Page 21: Mobile Development. A primer

Psion EPOC

● Graphical OS● PDAs with apps● EPOC16: Open Programming Language

PROC main:

PRINT "Hello World!"

PAUSE 40

ENDP

● EPOC32 (1997): C++ but mostly closed● EPOC32 becomes Symbian (1998)

Page 22: Mobile Development. A primer

Palm Zire(2002)

Image CC BY 3.0 by Soxred93 http://commons.wikimedia.org/wiki/File:Zirepalm.JPG

Page 23: Mobile Development. A primer

Palm OS

● Launched in 1996 and still alive!○ Now called WebOS

● C/C++/Pascal● Java was briefly available● No drivers for DBMS

○ developers need to use middleware● First system to provide emulators

Page 24: Mobile Development. A primer

Symbian

● A long and troubled story...● 1998: Psion becomes Symbian Ltd.

○ participation by Ericsson, Motorola, Nokia● 2008: Nokia acquires Symbian Ltd.

○ establishment of Symbian Foundation○ most Nokia devices run Symbian○ licensing issues

● 2011: Nokia partners with Microsoft. Symbian dies.

Page 25: Mobile Development. A primer

Symbian

● S60 = Native graphics toolkit (for Nokia, 2001)● QT framework (Symbian 3, 2010)● Development in

○ Java MIDP○ C++○ Python○ Flash

Page 26: Mobile Development. A primer

Symbian

● One (major) weakness: platform fragmentation

source: Wikipedia “S_60”

Page 27: Mobile Development. A primer

J2ME / Java ME

● Stripped down version of Java● Foundation standards

○ CLDC 1.0, 1.1, … (defines basic set of libraries)○ MIDP 1.0, 2.0, 3.0 (defines APIs)

■ apps are called “midlets”● Extensions, e.g.

○ JSR #82 Bluetooth○ JSR #179 Location API

Page 28: Mobile Development. A primer

J2ME / Java ME

● Modern framework○ Provides configurable simulators○ Coding of application lifecycle

● Relatively successful○ 2.1B Java ME enabled mobile phones

● Problems○ memory footprint○ device fragmentation

Page 29: Mobile Development. A primer

J2ME / Java ME

import javax.microedition.midlet.*;import javax.microedition.lcdui.*;

public class HelloWorld extends MIDlet implements CommandListener { private Command exitCommand; private TextBox tbox;

public HelloWorld() { exitCommand = new Command("Exit", Command.EXIT, 1); tbox = new TextBox("Hello world MIDlet", "Hello World!", 25, 0); tbox.addCommand(exitCommand); tbox.setCommandListener(this); }

protected void startApp() { Display.getDisplay(this).setCurrent(tbox); }

protected void pauseApp() {

}

protected void destroyApp(boolean bool) {

}

public void commandAction(Command cmd, Displayable disp) { if (cmd == exitCommand) { destroyApp(false); notifyDestroyed(); } }

}

Page 30: Mobile Development. A primer

J2ME / Java ME

import javax.microedition.midlet.*;import javax.microedition.lcdui.*;

public class HelloWorld extends MIDlet implements CommandListener { private Command exitCommand; private TextBox tbox;

public HelloWorld() { exitCommand = new Command("Exit", Command.EXIT, 1); tbox = new TextBox("Hello world MIDlet", "Hello World!", 25, 0); tbox.addCommand(exitCommand); tbox.setCommandListener(this); }

protected void startApp() { Display.getDisplay(this).setCurrent(tbox); }

protected void pauseApp() {

}

protected void destroyApp(boolean bool) {

}

public void commandAction(Command cmd, Displayable disp) { if (cmd == exitCommand) { destroyApp(false); notifyDestroyed(); } }

}

Page 31: Mobile Development. A primer

Opera Mini(2007)

Image CC BY 2.0 by Johan Larsson https://www.flickr.com/photos/johanl/4424185115

Page 32: Mobile Development. A primer

Opera Mini

● Mobile-oriented web browser● Reformats web pages to a “compressed” version

○ all content goes through proxy server● Pilot project started in 2004, launched 2007● Growing interest in mobile web standards

Page 33: Mobile Development. A primer

HTC Dream(2008)

Image GPL by Akela NDE http://en.wikipedia.org/wiki/File:HTC_Dream_Orange_FR.jpeg

Page 34: Mobile Development. A primer

Android

● Founded in 2003, acquired by Google in 2005● Based on Linux● Open Handset Alliance (2007)

○ HTC, Sony, Samsung, T-Mobile, Texas Instruments, etc…

● Nexus devices○ Nexus One (2010)

Page 35: Mobile Development. A primer

iOS

● iPhone launched in 2007 with iOS 1.x○ iPod Touch and iPad follow

● Developers not welcome until March 2008○ iPhone SDK released (iPhone OS)○ iOS was “a version of OS X” before then

● Apple did not want an “app economy”○ issues with control, market submission, etc…

Page 36: Mobile Development. A primer

iOS

● Controversies with developers and suppliers● Java and Flash originally not allowed● Competition wars

○ Sun agrees with Apple and Java gets in○ Adobe discontinues Flash mobile (2011)

Page 37: Mobile Development. A primer

HP Jornada 680(1998)

Image CC BY 2.0 by Noah (ax0n) https://www.flickr.com/photos/kc-bike/2532722221

Page 38: Mobile Development. A primer

Windows Mobile

● Microsoft joined the market early○ Windows CE (1996)○ Pocket PC (2000)○ Windows Mobile 2003○ Windows Mobile 5, 6 (2005)○ Windows Phone 7, 8 (2010)

● Windows 8 unifies desktop & mobile platforms

Page 39: Mobile Development. A primer

Windows Mobile

● Development with Microsoft tools● From Windows Phone 7, also web technologies● Windows Mobile lost momentum

Page 40: Mobile Development. A primer

#1.2In the public sector...

Page 41: Mobile Development. A primer

We are not ‘appy...

● (Tom Loosemore, GDS, 2013)

Stand-alone mobile apps will only be considered once the core web service works well on mobile devices, and if specifically agreed with the Cabinet Office.

(GDS Strategy, Action 6)

● Gov.Uk doesn’t have apps○ website adapts to mobile screens○ use of CSS3 technologies, media queries

Page 42: Mobile Development. A primer

...but we are!

● Tracy Green, UK Parliament (2013)○ 11% traffic to site from mobile○ of which 90% from iPad

● 400+ MPs have iPads○ demand for native apps “because they work

better”

Page 43: Mobile Development. A primer

Image CC BY-NC 2.0 by IDEO https://www.flickr.com/photos/ideopostcards/6334836459/

The PM wanted an app

Page 44: Mobile Development. A primer

Number 10 Dashboard

● (No one has ever seen it)● iPad app (maybe)● Purpose-built for the PM● By Adzuna (according to the FT)● Intranet front-end (according to The Register)

○ presumably a custom front-end to data.gov.uk● Dashboard of stats and data visualisation

Page 45: Mobile Development. A primer

HMRC Tax Calculator

● Native iOS/Android app

Page 46: Mobile Development. A primer

ParliQuiz

● Developed with “PugPig”○ publishing system○ £4K per year per single app

Page 47: Mobile Development. A primer

MyConstituency

● Hybrid app○ iPad only vs any Android○ not the same version

Page 48: Mobile Development. A primer

Some suggestions...

● ONS developed a case study about “MyConstituency”○ It meets the needs of MPs and their staff○ It engages with the general public○ Mini-tender: no big procurement drive!○ Tips

■ internal resources to handover app after project■ be specific about API / web service■ allow for flexibility

Page 49: Mobile Development. A primer

#1.3Some stats

Page 50: Mobile Development. A primer

<Stats slides omitted from SlideShare due to licensing. Contact me for details>

Page 51: Mobile Development. A primer

#2Modern mobile development

concepts

Page 52: Mobile Development. A primer

In this module...

● iOS, Windows 8 Phone, Android, and more● For each platform:

○ system architecture○ development model○ languages○ data storage○ UI building

● Markets

Page 53: Mobile Development. A primer

#2.1iOS

Page 54: Mobile Development. A primer

Assumptions

Focus on iOS 7● released in September 2013● it runs on iPhone 4 and later, iPad 2 and later● 87% of iOS devices (6/4/2014)● iOS 8 / Swift are currently beta

Page 55: Mobile Development. A primer

Basics

● Layered system architecture● MVC model● Objective-C● Interface Builder

● Apps are object (of type UIApplication)● Mac OS X required● XCode: iOS SDK + iOS Simulator

Page 56: Mobile Development. A primer

Tools: Xcode + iOS SDK

Page 57: Mobile Development. A primer

Tools: iOS Simulator

Page 58: Mobile Development. A primer

System Architecture: Abstraction Layers

Core OS

Core Services

Media

Cocoa Touch

These layers provide “Frameworks” to be added to any iOS project to provide certain functionalities

Page 59: Mobile Development. A primer

System Architecture: Abstraction Layers

Core OS

Core Services

Media

Cocoa Touch

Low-level features: security, communications, I/O, maths, networking, etc...

Page 60: Mobile Development. A primer

System Architecture: Abstraction Layers

Core OS

Core Services

Media

Cocoa Touch

System Services: Core Foundation, Foundation, iCloud, Automatic Reference Counting (ARC), Grand Central Dispatch (GCD), in-App Purchase, SQLite, Core Data, Core Location, etc...

Page 61: Mobile Development. A primer

System Architecture: Abstraction Layers

Core OS

Core Services

Media

Cocoa Touch

UIKit, Core Graphics, Core Animation, Core Audio, Core Media, AV Foundation, etc...

Page 62: Mobile Development. A primer

System Architecture: Abstraction Layers

Core OS

Core Services

Media

Cocoa Touch Storyboards, Push & Local Notifications, Gesture Recognisers, iAd, etc...

Page 63: Mobile Development. A primer

Model View Controller (MVC)

● Software Design Pattern● Separation of Data, UI, Logic

○ Model encapsulates data ○ View displays user interface○ Controller ties model to the view

● We will see this at work in the next session

Page 64: Mobile Development. A primer

Model View Controller (MVC)

ModelThe Model is about Data● data functions● data objects● data classes● i.e. data store + procedures that can access it

Page 65: Mobile Development. A primer

Model View Controller (MVC)

Model

View

The View is about User Interface● UI elements: buttons, sliders, text fields● object / classes / functions ● (or Storyboards / Interface Builder)

Page 66: Mobile Development. A primer

Model View Controller (MVC)

Model

View

The Model knows nothing about the UI

Page 67: Mobile Development. A primer

Model View Controller (MVC)

Model

View

Controller

The Controller is about bi-directional Orchestration● it intercepts user actions on the UI (View)● modifies the data accordingly (Model)

or● it detects data changes (Model)● modifies the UI accordingly (View)

Page 68: Mobile Development. A primer

Model View Controller (MVC)

Model

View

Controller

Page 69: Mobile Development. A primer

Model View Controller (MVC)

Model

View

Controller

user action

data change

Page 70: Mobile Development. A primer

Model View Controller (MVC)

Model

View

Controller

UI update

data changenotification

Page 71: Mobile Development. A primer

Model View Controller (MVC)

To accomplish communications we use links ● Outlets

○ from the controller to the view ○ to access info of an UI element

■ e.g. access the text typed in a text field● Actions

○ from the view to the controller ○ they announce an action on the UI

■ e.g. detect a button click, perform an action

Page 72: Mobile Development. A primer

Objective-C

● Object-oriented○ strict superset of C○ object syntax from Smalltalk

● Message passing to object instances○ i.e. not method calling

● Used on Mac OS X (Cocoa) and iOS (Cocoa Touch)

Page 73: Mobile Development. A primer

Objective-C: Message Passing

C++

Object* obj;

obj->method(argument);

Java

Object obj;

obj.method(argument);

Objective-C

Object* obj;

[obj method:argument];

Page 74: Mobile Development. A primer

Objective-C: Hello, world!

/* hello.h */

# import <Foundation/Foundation.h>

@interface Hello : NSObject

-(void)sayHello:(char*)name;

@end

Page 75: Mobile Development. A primer

Objective-C: Hello, world!

/* hello.m */

# import "hello.h"

@implementation Hello

-(void)sayHello:(char*)name {

printf("Hello, %s!\n", name);

}

@end

Page 76: Mobile Development. A primer

Objective-C: Hello, world!

/* app.m */

# import "hello.h"

int main() {

Hello* myhello = [Hello new];

char* name = "Joe";

[myhello sayHello:name];

}

To compile: $ clang -lobjc -o app app.m hello.m

Page 77: Mobile Development. A primer

Objective-C: Protocols

● Add set of expected behaviours to an object○ or, in official speak, define messaging contracts

● An object can conform to a protocol● In practice: methods to be implemented

○ some required, some optional

Page 78: Mobile Development. A primer

Objective-C: Protocols

/* politehello.h */

#import <Foundation/Foundation.h>

@protocol PoliteHello <NSObject>

-(void)helloFriend;

-(void)helloColleague ;

-(void)helloPrimeMinister ;

@end

Page 79: Mobile Development. A primer

Objective-C: Protocols

/* hello.h */

#import <Foundation/Foundation.h>

#import "politehello.h"

@interface Hello : NSObject <PoliteHello>

-(void)sayHello:(char*)name;

@end

Page 80: Mobile Development. A primer

Objective-C: Protocols

/* hello.m */

# import "hello.h"

@implementation Hello

-(void)sayHello:(char*)name {

printf("Hello, %s!\n", name);

}

-(void)helloFriend {

printf("Hey!\n");

}

-(void)helloColleague {

printf("How was your weekend? \n");

}

-(void)helloPrimeMinister {

printf("Good morning, sir \n");

}

@end

Page 81: Mobile Development. A primer

Delegation

● Software pattern, Obj-C protocol● Let an object control another object● Use a central object to customize the behaviour of

several others● Delegating object A keeps reference to delegate

object B● A sends a message to B● B reacts by updating UI/state

Page 82: Mobile Development. A primer

Data Source

● Similar to a Delegate● Delegated control of data● Outlet held by View objects● Implemented via Obj-C protocol

Page 83: Mobile Development. A primer

Table Data Source

Page 84: Mobile Development. A primer

Table Data Source

Page 85: Mobile Development. A primer

Table Delegate

Page 86: Mobile Development. A primer

Table Delegate

Page 87: Mobile Development. A primer

Application Delegate

● Most important delegate in an iOS project● Delegate for the UIApplication object● Starting point for coding● Startup/shutdown tasks

○ e.g. initialise database, verify license, etc...● App-wide tasks

○ e.g. handle push notifications, support window orientation, etc...

Page 88: Mobile Development. A primer

Application Delegate

Page 89: Mobile Development. A primer

Interface Builder

“UI Drawing” tool included in XCode● Add Window object● Add Content View*● Add UI Controls (buttons, text fields, etc…)● Add basic navigation between views (Storyboards)

(*) Views are hierarchical ○ i.e. they are containers for other subviews

Page 90: Mobile Development. A primer

Interface Builder

Page 91: Mobile Development. A primer

Storyboards

● Interface Builder on steroids● Define navigation relationships among Scenes● Each Scene has an associated view hierarchy● Scenes are connected by segues or relationships

○ segue = transition between two view controllers■ push, modal, custom, unwind

○ relationship = hierarchy

Page 92: Mobile Development. A primer

Storyboards

Page 93: Mobile Development. A primer

Auto Layout

● Define relationships between UI elements● Mathematical constraints● UI reacts dynamically to changes

○ screen size, orientation, localization, etc...

Page 94: Mobile Development. A primer

Auto Layout

Page 95: Mobile Development. A primer

Navigation Controllers

● To manage a stack of view controllers● To provide a drill-down interface for hierarchical

content● Several types, according to context & device type

○ Tab Bar○ Page View○ Split View○ etc…

Page 96: Mobile Development. A primer

Data Storage

● Preferences (key/value)● File system (for large files)● SQLite

○ a lightweight relational database○ de facto industry standard for embedded apps

● CoreData Framework○ object oriented wrapper○ infrastructure for search, save, restore, etc…

● iCloud (and other cloud storage providers)

Page 97: Mobile Development. A primer

#2.2Windows 8 Phone

Page 98: Mobile Development. A primer

Assumptions

Focus on Windows 8.1 Phone● released in October 2013● it runs on several architectures

○ IA-32, x64, ARMv7● marketed as “update” for Windows ● development overlaps with Windows 8 desktop

○ Windows Store and Windows Phone Store apps are converging into Windows Runtime apps

Page 99: Mobile Development. A primer

Windows 8 (desktop)Used with Permission from Microsoft

Page 100: Mobile Development. A primer

Windows 8 (phone)Used with Permission from Microsoft

Page 101: Mobile Development. A primer

● One architecture, several development options○ flow control languages○ UI definition language

● Windows 8.1 + Visual Studio Express 2013

Basics

Page 102: Mobile Development. A primer

Languages

Used with Permission from Microsoft

Page 103: Mobile Development. A primer

Differences

● Each language has a corresponding app model○ i.e. a set of files, design patterns, app entry point

● Certain languages more suitable to certain apps○ e.g. C++ / DirectX are good for 3D games

● Otherwise, philosophy is: use what you know● For this course, our choice is JavaScript / HTML5

Page 104: Mobile Development. A primer

Windows Runtime

● Often referred to as WinRT● Successor of Win32 API

○ Based on COM/.NET● Platform-homogenous app architecture for Win 8

○ unifies Windows 8 and Windows 8 Phone● Supports several languages

Page 105: Mobile Development. A primer

Tools: Visual Studio 2013 ExpressUsed with Permission from Microsoft

Page 106: Mobile Development. A primer

Used with Permission from Microsoft

Tools: Emulator

Page 107: Mobile Development. A primer

UI definition

● In standard HTML5...● ...plus “Microsoft Phone WinJS” libraries

<script src=”//Microsoft.Phone.WinJS.2.1/js/base.js”></script>

<script src=”//Microsoft.Phone.WinJS.2.1/js/ui.js”></script>

● these libraries cover UI controls and behaviours

Page 108: Mobile Development. A primer

Application Entry Point

● method called by the system to start the app● onactivated() in js/default.js● main UI defined in default.html● allows to detect how the app was started

○ i.e. from launch, suspension, etc...

Page 109: Mobile Development. A primer

Application Entry Point

var app = WinJS.Application;

var activation = Windows.ApplicationModel.Activation;

app.onactivated = function (args) {

if (args.detail.kind === activation.ActivationKind.launch) {

if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {

// TODO: This application has been newly launched. Initialize

// your application here.

} else {

// TODO: This application has been reactivated from suspension.

// Restore application state here.

}

args.setPromise(WinJS.UI.processAll());

}

};

Page 110: Mobile Development. A primer

Application Lifecycle

Not Running Suspended

Running

Activated

Resuming

Suspending

Page 111: Mobile Development. A primer

Application Entry Point

var app = WinJS.Application;

var activation = Windows.ApplicationModel.Activation;

app.onactivated = function (args) {

if (args.detail.kind === activation.ActivationKind.launch) {

if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {

// TODO: This application has been newly launched. Initialize

// your application here.

} else {

// TODO: This application has been reactivated from suspension.

// Restore application state here.

}

args.setPromise(WinJS.UI.processAll());

}

};

Page 112: Mobile Development. A primer

UI.processAll()

● scans default.html for WinJS Controls○ if it finds any, it initialises them

● enclosed in setPromise to display splash screen until UI loading is complete

Page 113: Mobile Development. A primer

JavaScript

● Standard JavaScript ● Win JS = Open Source JavaScript library

○ helpers that expose the Windows Runtime○ provides page control, promises, data-binding○ allows Windows UI controls in HTML

■ using data binding and templating

Page 114: Mobile Development. A primer

Asynchronous Programming

● CommonJS Promises “A”● Promise = eventual result from an async operation● Object with “future value” is returned● then() function● In lay terms

○ when you finish task X, perform Y○ promise is Y’s result handler

Page 115: Mobile Development. A primer

Asynchronous Programming

● Promise object offers methods to deal with result● then()and done() functions

WinJS.Promise.timeout(1500, WinJS.xhr({ url: "http://www.microsoft.com" })

.then(function complete(result) {

WinJS.log && WinJS.log( "Downloaded the page" );

},

function error(error){

// ...

WinJS.log && WinJS.log( "Got error: " + error.statusText);

}

));

Page 116: Mobile Development. A primer

UI

● Standard HTML controls<button id="helloButton">Say "Hello"</button>

● WinJS controls<div

id="toggleControlDiv"

data-win-control="WinJS.UI.ToggleSwitch"

data-win-options="{title: 'Greeting Color'}">

</div>

Page 117: Mobile Development. A primer

UI actions

● by event handling○ register an event listener○ in app.onactivated(), after args.setPromise()

var helloButton = document.getElementById("helloButton");

helloButton.addEventListener("click", buttonHandler, false);

Page 118: Mobile Development. A primer

UI actions

● buttonHandler() is a standard JavaScript function

function buttonHandler(eventInfo) {

var inputString = document.getElementById("input").value;

document.getElementById("output").innerText = inputString;

}

Page 119: Mobile Development. A primer

● done in CSS3

● defaults for dark and light UI themes are provided

● add in /css/default.css

● e.g..toggle-on {

color:blue;

}

UI styling

Page 120: Mobile Development. A primer

● Effective way to add data into HTML/WinJS control

● Define UI control, define data, bind data to control

○ if data change, UI control is updated

○ e.g. useful with lists

Data Binding

Page 121: Mobile Development. A primer

Define binding for UI element:<span id="namespan" data-win-bind="innerText: name"></span>

Then, in the Javascript:var person = { name: "Fran" };

var personSpan = document.querySelector('#nameSpan');

WinJS.Binding.processAll(personSpan, person);

Data Binding

Page 122: Mobile Development. A primer

● It’s HTML, so we can use linking

● Single-page Navigation

○ Microsoft-recommended

○ There are still multiple files

○ Better for transferring app context

○ One “central” PageControl object loads other files

Navigation

Page 123: Mobile Development. A primer

● Several navigation patterns can be combined

○ due to HTML, developer has maximum freedom

● Typical examples

○ List with drill-down

○ Central app hub (panoramic view)

○ App tabs

○ Page shuffle

Navigation Patterns

Page 124: Mobile Development. A primer

Navigation Example: List with drill-down

Used with Permission from Microsoft

Page 125: Mobile Development. A primer

Navigation Example: Page Shuffle

Used with Permission from Microsoft

Page 126: Mobile Development. A primer

Navigation Example: Central app hub

Used with Permission from Microsoft

Page 127: Mobile Development. A primer

Navigation Example: Central app hub

Used with Permission from Microsoft

Page 128: Mobile Development. A primer

● User Data: document, files, etc…

○ File system

○ One Drive

○ HTML5 File API

Data Storage

Page 129: Mobile Development. A primer

● App Data: state, configuration, preferences, etc…

○ App Data API for WinRT

○ IndexdDB (ISAM)

○ Extensible Storage Engine (ISAM)

○ HTML5 Web Storage

○ WinJS.Application.sessionState, local, roaming

Data Storage

Page 130: Mobile Development. A primer

#2.3Android

Page 131: Mobile Development. A primer

Assumptions

● Android 4.4 “KitKat”○ released in October 2013

● 13.6% of android installs○ Android 2.3 “Gingerbread” is at 14.9%○ Android 4.0 “Ice Cream Sandwich” 12.3%

● Android versions have had a complicated history...

Page 132: Mobile Development. A primer

Basics

● App lifecycle + MVC model● Java (Dalvik VM) + Native C Code (Bionic)● XML-based UI design● Android = software stack

○ OS based on Linux kernel ○ Middleware, Core Applications, SDK

● Eclipse, Android SDK, ADT, Simulator○ on PC, Mac, Windows, …

Page 133: Mobile Development. A primer

Architecture

CC-BY-SA 3.0 by Smieh

Page 134: Mobile Development. A primer

Manifest

● Synoptic view of an application○ Lists activities○ Adds permissions○ Register intents○ and more...

Page 135: Mobile Development. A primer

Activities

● Apps are collections of Activities○ Activities are Java objects○ Activities provide a screen

● Each Activity is the base for UI○ They can use Views and Fragments

■ Views = widgets (buttons, fields, etc…)■ Fragments = components with encapsulated

code

Page 136: Mobile Development. A primer

Activity Lifecycle

Image: Apache License from developer.google.com

Page 138: Mobile Development. A primer

Intents

Image: Apache License from developer.google.com

Page 139: Mobile Development. A primer

Intents

● Runtime binding between code in different apps● Mostly used to launch activities● Explicit

○ specify exact class to be run● Implicit

○ include information to help the system “decide”○ concept of Intent Resolution

Page 140: Mobile Development. A primer

Intents

● Activities can register Intent Filters in the Manifest● Intents are used intra-app and between apps<activity class=".NotesList">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

</intent-filter>

<intent-filter>

<action android:name="android.intent.action.VIEW" />

<action android:name="android.intent.action.PICK" />

<data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />

</intent-filter>

</activity>

Code: Apache License from developer.google.com

Page 141: Mobile Development. A primer

Intents

● Programmatically, switch to a different activity

Intent intent = new Intent(this, DisplayMessageActivity.

class);

String message = “Hello”;

intent.putExtra(EXTRA_MESSAGE, message);

startActivity(intent);

Code: Apache License from developer.google.com

Page 142: Mobile Development. A primer

Intents

● Programmatically, switch to a different activity

Intent intent = new Intent(this, DisplayMessageActivity.

class);

String message = “Hello”;

intent.putExtra(EXTRA_MESSAGE, message);

startActivity(intent);

Code: Apache License from developer.google.com

Data sharing

Page 143: Mobile Development. A primer

UI

● “Roughly” MVC ● Views are defined programmatically or in XML

○ Layout Inflater● Activity: setContentView()

○ views are nested● Hierarchy of Views grouped in View Groups

○ views are single UI widgets○ groups define how the views are laid out

Page 144: Mobile Development. A primer

XML Layout

main_layout.xml<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<TextView android:id="@+id/text"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello, I am a TextView" />

<Button android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello, I am a Button" />

</LinearLayout>Code: Apache License from developer.google.com

Page 145: Mobile Development. A primer

XML Layout

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main_layout);

}

Code: Apache License from developer.google.com

Page 146: Mobile Development. A primer

XML Layout

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main_layout);

}

Code: Apache License from developer.google.com

Page 147: Mobile Development. A primer

Resources & R

● All resources are under a folder called “res”○ drawables○ layouts○ localised strings

● Android exposes them through the R class○ R.layout.main_layout○ Smart system for localisation

■ values -> R.values.string■ values-en -> R.values.string

Page 148: Mobile Development. A primer

Resources & R

● All resources are under a folder called “res”○ drawables○ layouts○ localised strings

● Android exposes them through the R class○ R.layout.main_layout○ Smart system for localisation

■ values -> R.values.string■ values-en -> R.values.string

Page 149: Mobile Development. A primer

Images

● R.drawable.<image> makes access easy but…● ...there is massive diversity in device capabilities

○ drawable-hdpi○ drawable-ldpi○ drawable-mdpi○ etc…

● Screen support is a major pain

Page 150: Mobile Development. A primer

Images

Image & Text: Apache License from developer.google.com

Page 151: Mobile Development. A primer

Data Storage

● Shared Preferences○ key-value pairs of primitive types

● Internal and External File Storage● SQLite Database

Page 152: Mobile Development. A primer

UI Actions

● 2 options: define onClick function...

<?xml version="1.0" encoding="utf-8"?>

<Button xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/button_send"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/button_send"

android:onClick="sendMessage" />

public void sendMessage(View view) {

// Do something in response to

button click

}

Code: Apache License from developer.google.com

Page 153: Mobile Development. A primer

UI Actions

● ...or create event listener

Button button = (Button) findViewById(R.id.button_send);

button.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

// Do something in response to button click

}

});

Code: Apache License from developer.google.com

Page 154: Mobile Development. A primer

Asynchronous Programming

● Unresponsive apps trigger the “ANR” dialog● Implement AsyncTask to run in background

Image: Apache License from developer.google.com

Page 155: Mobile Development. A primer

Asynchronous Programming

● Define Task...private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

protected Long doInBackground (URL... urls) {

int count = urls.length;

long totalSize = 0;

for (int i = 0; i < count; i++) {

totalSize += Downloader .downloadFile (urls[i]);

publishProgress ((int) ((i / (float) count) * 100));

// Escape early if cancel() is called

if (isCancelled ()) break;

}

return totalSize ;

}

// This is called each time you call publishProgress()

protected void onProgressUpdate (Integer... progress) {

setProgressPercent (progress[0]);

}

protected void onPostExecute (Long result) {

showNotification ("Downloaded " + result + " bytes");

}

}

Page 156: Mobile Development. A primer

Asynchronous Programming

● launch and continue with other activities● at the end, onPostExecute() will update with results

new DownloadFilesTask().execute(url1, url2, url3);

Page 157: Mobile Development. A primer

#2.4Alternatives

Page 158: Mobile Development. A primer

What else?

● Cross-platform native development● 100% Mobile Web● UI Frameworks

○ CSS libraries○ MVC-based

Page 159: Mobile Development. A primer

Apache Cordoba/PhoneGap

● Set of APIs to access native functions from JavaScript○ camera, geolocation, etc...

● Develop mobile apps in HTML, CSS, Javascript○ combine with UI framework

■ jQuery Mobile, Dojo Mobile, Sencha Touch, ...● “Package” it in a native app using the platform SDK● Supports: iOS, Android, Blackberry, Windows Phone,

Palm WebOS, Bada, Symbian (in future: Firefox OS)

Page 160: Mobile Development. A primer

Mobile Web

● “Apps are overrated”● Make web sites mobile-ready● HTML5, jQuery, JavaScript● Use Open Standards● Easier for accessibility

Page 161: Mobile Development. A primer

Sencha Touch

● HTML5 framework● Provides themes for most mobile platforms● Based on MVC pattern

Page 162: Mobile Development. A primer

jQuery Mobile

● HTML5-based UI system● Responsive web sites● Based on jQuery ● Provides

○ Ajax navigation○ Touch events○ Widgets

Page 163: Mobile Development. A primer

<Stats on cross-platform framework omitted due to licensing. Contact me for details.>

Page 164: Mobile Development. A primer

What lies ahead?

● Firefox OS● IndiePhone● FairPhone● ...and many others

Page 165: Mobile Development. A primer

#2.5App Distribution & conclusions

Page 166: Mobile Development. A primer

Markets

● Publicly available app-stores○ “Private apps” with authentication

● Android & Windows allow direct sideloading○ Recommended in Windows, not in Android

● Enterprise app distribution○ in iOS (£299/year)○ in Android (no extra cost)

Page 167: Mobile Development. A primer

The screen size war

Android iOSImages source: OpenSignal

Page 168: Mobile Development. A primer

The screen size war

● Fragmentation is predominant in the Android market○ Good for users○ Bad for developers

● Tablets are less affected○ Once you get past 7”, difference not that important

Page 169: Mobile Development. A primer

#3Hello, World!

Page 170: Mobile Development. A primer

#3.1iOS

Page 171: Mobile Development. A primer
Page 172: Mobile Development. A primer
Page 173: Mobile Development. A primer
Page 174: Mobile Development. A primer
Page 175: Mobile Development. A primer
Page 176: Mobile Development. A primer
Page 177: Mobile Development. A primer
Page 178: Mobile Development. A primer
Page 179: Mobile Development. A primer
Page 180: Mobile Development. A primer
Page 181: Mobile Development. A primer
Page 182: Mobile Development. A primer
Page 183: Mobile Development. A primer
Page 184: Mobile Development. A primer
Page 185: Mobile Development. A primer
Page 186: Mobile Development. A primer
Page 187: Mobile Development. A primer
Page 188: Mobile Development. A primer
Page 189: Mobile Development. A primer
Page 190: Mobile Development. A primer
Page 191: Mobile Development. A primer

#3.2Windows 8 Phone

Page 192: Mobile Development. A primer
Page 193: Mobile Development. A primer
Page 194: Mobile Development. A primer
Page 195: Mobile Development. A primer
Page 196: Mobile Development. A primer
Page 197: Mobile Development. A primer

Press the “play” button

Page 198: Mobile Development. A primer

Keep an eye on the console

Page 199: Mobile Development. A primer
Page 200: Mobile Development. A primer

#4Let’s get some practice

Page 201: Mobile Development. A primer

Exercise 0: Hello, World!

● Display a static “hello” string● iOS

○ view controllers, storyboards, outlets● Windows

○ simple html

Page 202: Mobile Development. A primer

Exercise 1: Basic interaction

● Display a dynamic “hello” string○ text and push a button

● iOS○ outlets & actions

● Windows○ event handlers

Page 203: Mobile Development. A primer

Exercise 2: Populate a table

● Display a table with some data from an array● iOS

○ table view, data source● Windows

○ list view, data-binding

Page 204: Mobile Development. A primer

Exercise 3: Pie Chart

● Display a simple pie chart● iOS

○ core plot● Windows

○ Raphael.js

Page 205: Mobile Development. A primer

Exercise 4: Line Chart

● Display a simple pie chart● iOS

○ core plot● Windows

○ Raphael.js

Page 206: Mobile Development. A primer

Exercise 5 (optional): Navigation

● Play with building a navigation framework● iOS

○ storyboards● Windows

○ page control tutorial

Page 207: Mobile Development. A primer

And more...

● Let’s put this all together● Display data from the Guardian?

Page 208: Mobile Development. A primer

Fin.