1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

102
1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang

Transcript of 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Page 1: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

1

Mobile Software Development Framework

10/2/2012

Y. Richard Yang

Page 2: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

2

Admin.

Homework 2

Start to think about project

Page 3: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

3

Recap: OFDM

Basic: use multiple subcarriers to reduce symbol rate per carrier

Key idea 1: orthogonal subcarriers to avoid inter-carrier-interference (ICI): chose each subcarrier frequency so that an integral number of cycles in a symbol period

Key idea 2: iFFT as an efficient algorithm for modulation on multiple subcarriers

Idea 3: cyclic prefix (guard interval)

Page 4: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

4

Recap: Summary of Wireless PHY

Page 5: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

5

Recap: GNURadio

A software development toolkit that provides signal processing blocks to implement software-defined radio systems.

Some key ideas Hybrid software system (Python/C++) Composite pattern to build a hierarchy of blocks

• http://en.wikipedia.org/wiki/Composite_pattern Internal scheduler to orchestrate data flows

among blocks Define gr_block as a reusable base so that

defining a new block typically means only rewrite general_work and forecast

Page 6: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

6

Recap: TinyOS

A free and open source component based operating system and platform targeting wireless sensor networks (WSNs)

Some design features TinyOS: Generate customized

OS + application: support one appat a time but flexible reprogramming

Page 7: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

7

TinyOS: Software Concepts

A TinyOS consists of one or more components/modules linked together software components

motivated by hardware component

Each component specifies: it provides some interfaces

• allows other components to control it

also uses some interfaces• control other components

Page 8: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

8

Interface

An interface declares a set of

functions called commands that provider must implement

another set of functions called events that the interface user must implement

A uses interfaces I1 and I2

B provides I1 C provides I2

commands events commands eventsI1 I2

C provides I3

Page 9: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

9

Interface: Examples

StdControl.nc

interface StdControl {  command result_t init();  command result_t start();  command result_t stop();}

Timer.nc

interface Timer {

command result_t start(

char type,

uint32_t interval); 

command result_t stop(); 

event result_t fired();

}

ADC.nc

interface ADC {

async command result_t getdata(); 

async command result_t getContinuousData(); 

event result_t dataReady(uint 16_t data);

}

Page 10: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

10

Example Application

A simple TinyOS application which periodically reads in the light intensity value, computes a moving average, displays it on the LED

Page 11: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

11

Module: Definition

SenseTaskM.nc

module SenseTaskM {

provides {

interface StdControl;

}

uses {

interface Timer;

interface ADC;

interface StdControl as ADCControl;

interface Leds;

}

}

A uses interfaces I1 and I2

B provides I1 C provides I2

commands events commands eventsI1 I2

C provides I3

Page 12: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

12

Module: Implementation

Define commands and event

handlers

frame (storage)• statically allocated, fixed

size to know memory requirement and avoid overhead of dynamic allocation

See SenseTaskM.nc

Component

Internal StateInternal Tasks

Commands Events

Page 13: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

13

Linking Components

Two types of components:

modules: individual components

configurations : assemble components together, connecting interfaces (objects) used by components to interfaces (objects) provided by others

• See SenseTask.nc

Page 14: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

14

TinyOS Execution Model

A uses interfaces I1 and I2

B provides I1 C provides I2

commands events commands events

C provides I3

Page 15: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

15

TinyOS Execution Model

Concurrency model: only two threads long running tasks that can be interrupted by hardware

event handlers

Each task is atomic with respect to other tasks run to completion, but can be preempted by events the task scheduler is a simple FIFO scheduler

Tasks perform the primary computation work commands and event handlers post tasks call lower level commands signal higher level events schedule other tasks within a component

Page 16: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

16

Running tinyOS Program make mica ncc -o main.exe -target=mica SenseTask.nc avr-objcopy --output-target=srec main.exe

main.srec Use uisp to install

Page 17: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

17

A More Complete Sample Application Sensor network

monitoring monitor temperature and

light conditions periodically transmit

measurements to a base station

sensors can forward data for other sensors that are out of range of the base station

dynamically determine the correct routing topology for the network

Page 18: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

18

Internal Component Graph

RFM

Radio byte

Radio Packet

UART

UART Packet

I2C

Temp

Light

Active Messages

Clocksbit

byte

packet

Ad hoc Routing Applicationapplication

HW

SW

Page 19: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

19

Message Send Transition

Total propagation delay up the 5 layer radio communication stack is about 80 instructions

Timing diagram of event propagation

Page 20: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

20

Evaluation: Storage

Component Name Code Size (bytes)

Data Size (bytes)

RoutingAM_dispatchAM_temperatureAM_lightAMRADIO_packetRADIO_byteRFMLightTempUARTUART_packetI2C

884078

1463563348103108464

196314198

00

328

4040

81111

408

Processor_initTinyOS schedulerC runtime

17217882

3016

0

Total 3450 226

Scheduler only occupies 178 bytes

Complete application only requires 3 KB of instruction memory and 226 bytes of data (less than 50% of the 512 bytes available)

Only processor_init, TinyOS scheduler, and C runtime are required

Page 21: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

21

Evaluation: Timing

Operations Cost (cycles)

Time (µs)

Normalized to byte copy

Byte copy 8 2 1

Post an Event

Call a Command

Post a task to scheduler

Context switch overhead

10104651

2.52.5

11.512.7

5

1.251.25

66

Interrupt (hardware cost) 9 2.25 1

Interrupt (software cost) 71 17.75

9

Page 22: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Summary: TinyOS Components

provide commands andrequire callback hooks for event-driven programming

Configurations Link components

TinyOS an app (configuration)

at a time, linkingonly necessary components

Two threads exec one for event one for task

22

ADC.nc

interface ADC {

async command result_t getdata(); 

async command result_t getContinuousData(); 

event result_t dataReady(uint 16_t data);

} configuration SenseTask { // this module does not provide any interfaces}implementation{ components Main, SenseTaskM, LedsC, TimerC, DemoSensorC as Sensor;

Main.StdControl -> TimerC; Main.StdControl -> Sensor; Main.StdControl -> SenseTaskM;

SenseTaskM.Timer -> TimerC.Timer[unique("Timer")]; SenseTaskM.ADC -> Sensor; SenseTaskM.Leds -> LedsC;}

Page 23: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Discussion: Compare TinyOS/GNURadio

What are some similar software concepts?

What are some differences?

23

Page 24: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Discussion

Can we use GNURadio/TinyOS for writing mobile applications for mobile phones, or in other words, what are missing?

24

Page 25: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

25

Java2 Micro Edition (J2ME)

Page 26: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

26

Outline

Admin and recap Mobile/wireless development framework

GNURadio TinyOS J2ME

Page 27: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

27

Java Platforms

Java2 is divided into three platforms J2EE (Java2 Enterprise Edition)

• business applications

J2SE (Java2 Standard Edition)• general applications

J2ME (Java2 Micro Edition)• small devices such as mobile phone, PDA, car navigation

Oracle’s claims on Java on mobile devices http://www.java.com/en/about/

Page 28: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

28

J2ME Basic Concepts: Versioning To accommodate heterogeneous mobile

devices, define configurations and profiles

http://developers.sun.com/techtopics/mobility/getstart/articles/survey/

-A configuration provides fundamental services for a broad category of devices (e.g., lang, io, util)

- A profile supports higher-level services common to a more specific class of devices or market (e.g., life cycle, GUI)

-An optional package adds specialized services that are useful on devices of many kinds, but not necessary on all of them

Page 29: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

29

J2ME

128-512K mem16-32 bit proc

Upto 2M mem32 bit proc

Page 30: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

30

Example J2ME Configurations

Connected Limited Device Configuration (CLDC) 160 KB to 512 KB of total memory available 16-bit or 32-bit processor low power consumption and often operating with battery

power connectivity with limited bandwidth examples: cell phones, certain PDAs

Connected Device Configuration (CDC) 2 MB or more memory for Java platform 32-bit processor high bandwidth network connection, most often using

TCP/IP examples: set-top boxes, certain PDAs

Page 31: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

31

CLDC Available Packages

java.lang java.util java.io javax.microedition.io

Page 32: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

32

CLDC Classes Boolean Byte Character Class Integer Long Math Object Runnable Runtime Short String StringBuffer System Thread Throwable

Calendar Date Enumeration Hashtable Random Stack TimeZone Vector

ByteArrayOutputStream ByteArrayInputStream DataOuput DataInput DataInputStream DataOutputStream InputStream InputStreamReader OutputStream OutputStreamWriter PrintStream Reader Writer

java.lang java.util java.io

Page 33: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

33

Example J2ME Profiles

Mobile Information Device Profile (MIDP) GUI, multimedia and game functionality,

end-to-end security, and greater networked connectivity

mobile phones and entry level PDAs

Foundation Profile set of Java APIs that support resource-constrained devices

without a standards-based GUI system

Personal Profile Full set of AWT APIs, including support for applets and Xlets CDC + Foundation Profile + Personal Profile for high-end PDA

Page 34: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

34

Mobile Phone Framework

Page 35: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

35

MIDP Hardware

Memory (added to CLDC memory) 128 KB non-volatile for MIDP components 8 KB non-volatile for application persistent

data 32 KB volatile for KVM

Display screen 96x54 display depth 1-bit pixel shape (aspect ratio) 1:1

Page 36: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

36

MIDP Hardware

Input (one or more)one-handed keyboard (ITU-T phone

keypad)two-handed keyboard (QWERTY keyboard)or touch screen

Networking two-way wireless possibly intermittent limited bandwidth

Page 37: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

37

MIDP Packages

java.io java.lang java.util javax.microedition.io javax.microedition.lcdui javax.microedition.rms javax.microedition.midlet

javax.microedition.lcdui.game javax.microedition.media javax.microedition.media.contr

ol javax.microedition.pki

addition in version 2.0version 1.0

Page 38: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

38

MIDP Technology Stack

Mobile Information

Device Profile

KVMCLDC = KVM + J2ME Core

APIs in this

example DSP chip(e.g., ARM)

J2ME core APIs

YourMIDlet

Yellow Pages, train schedules and ticketing, games…

UI, HTTP networking...

Threads, no Floats…

32-bit RISC, 256K ROM, 256K Flash, 64K RAM

Page 39: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

MIDlet

GUI based

Each MIDP has one instance of Display• Display.getDisplay(this) to get the manager• At any instance of time at most one Displayable

object can be shown on the display device and interact with user– display.setCurrent(<Displayable object>)

39

Page 40: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

40

MIDlet

An MIDP application is called a MIDlet similar to the J2SE applet

A MIDlet moves from state to state in the lifecycle, as indicated

start – acquire resources and start executing

pause – release resources and become quiescent (wait)

destroy – release all resources, destroy threads, and end all activity

Pause

Active

Destroyed

startApp

destroyApp

pauseApp

destroyApp

Page 41: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

MIDP Visual Display

Each MIDP has one instance of Display

Display.getDisplay(this) to get the manager

At any instance of time at most one Displayable object can be shown on the display device and interact with user• display.setCurrent(<Displayable object>)

41

Page 42: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

MIDP Visual Display

Displayable Canvas

• GameCanvas

Screen• Alert, List, TextBox, Form

Form can contain multiple form items for organization Labels, Image Items, String Items, Text Fields, Date

Fields, Gauges, Choice Groups

42

Page 43: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

MIDP: User Interaction

Displayable objects can declare commands and declare a command listener: addCommand(Command cmd) addCommandListener()

Command(<label>, <type>, <priority>) Type: BACK, CANCEL, EXIT, HELP, ITEM, OK, SCREEN, and STOP

43

Page 44: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

44

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

public class HelloWorldMIDlet extends MIDletimplements CommandListener {

private Command exitCommand;private Display display;private TextBox t;

public HelloWorldMIDlet() { display = Display.getDisplay(this);exitCommand = new Command("Exit", Command.EXIT, 2);t = new TextBox(“CS434", "Hello World!", 256, 0);t.addCommand(exitCommand);t.setCommandListener(this);

}public void startApp() { display.setCurrent(t); }public void pauseApp() { }public void destroyApp(boolean unconditional) { }public void commandAction(Command c, Displayable s) {

if (c == exitCommand) {destroyApp(false);notifyDestroyed();

}}

}

Page 45: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

MIDP: Persistent State

Record store defined in javax.microedition.rms

Record store identified by name: static String[] listRecordStores();

recordStore = RecordStore.openRecordStore("scores", true);

recordId = addRecord(byte[] data, int offset, int numBytes);

getRecord(int recordId);

45

Page 46: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

46

Summary : J2ME

Scale down a popular programming environment to ease learning

Use virtual machines to mask device heterogeneity

Use configuration/profiling to handle device heterogeneity and avoid using lowest common denominator

MIDLet to manage app life cycle Displayable to visual display, commands and

provides command listener Introduce persistent record store

Page 47: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Discussion on J2ME

What designs of J2ME do you like and hence expect newer frameworks (e.g., IOS, Android) may have too?

What features do you think are missing in J2ME?

47

Page 48: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

48

Outline

Admin and recap Mobile/wireless development framework

GNURadio TinyOS J2ME Android

http://developer.android.com/index.html

Page 49: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Android

A mobile OS, application framework, and a set of applications OS

• Customized Linux kernel 2.6 and 3.x (Android 4.0 onwards)

– E.g., default no X Windows, not full set of GNU libs

Application development framework• Based on Java (J2SE not J2ME)• Dalvik Virtual Machine

49

Page 50: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Android Architecture

50

Page 51: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Poking Android OS

See http://developer.android.com/tools/workflow/index.html

Android SDK Manager (android) to start a simulator

Android debug bridge (adb) can connect to an Android device and start a shell on the device

Page 52: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Application Framework (Android): Key Concepts

Activity View External resources Service Intercommunications

52

Communication among apps: - Intent- broadcast- data provider

Page 53: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Activity

A single, focused thing that the user can do.

Interaction with users: creating a window to place UI views

full-screen windows, floating windows, embedded inside of another activity

Page 54: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Android Activity Life cycle

54

Page 55: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

View

A view component is a building block for user interface components.

Widget Toolbox TextView, EditText, Button, Form,

TimePicker… ListView Layout

• Positions of controls• LinearLayout, Relativelayout

http://developer.android.com/guide/tutorials/views/index.htm

Page 56: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

View by XML

Layout of visual interface

Java Code Initialize

Access TextView myTextView =

(TextView)findViewById(R.id.myTextView);

<?xml version=”1.0” encoding=”utf-8”?><LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:orientation=”vertical” android:layout_width=”fill_parent” android:layout_height=”fill_parent”><TextView android:id=”@+id/myTextView” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Hello World, HelloWorld”/></LinearLayout>

@Overridepublic void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main);}

main.xml

Page 57: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

User Interaction Event

onKeyDown. onKeyUp onTrackBallEvent onTouchEvent

myEditText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { … return true; } return false; }});}

registerButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) {….}}

Page 58: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Example: TipCal

58

Page 59: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Application Framework (Android): Key Concepts

Activity and view Visible screen for user interaction

External resources

59

Page 60: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

External Resources

60

Page 61: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Application Framework (Android): Key Concepts

Activity and view Visible screen for user interaction

External resources Service

61

Page 62: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Service: Working in Background A basic function of Android Service:

A facility for an application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application).

The system to schedule work for the service, to be run until the service or someone else explicitly stop it.

NO GUI, higher priority than inactive Activities Note

A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.

A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Page 63: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Application and Component Glues Intent

An intent is an abstract description of an operation to be performed.

To invoke operations from your own or others Can pass data back and forth between app.

Intent Filter Register Activities, Services, and Broadcast

Receivers as being capable of performing an action on a particular kind of data.

Page 64: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent Description <Component name> Action

Data Category, e.g., LAUNCHER

64

Page 65: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent Usage

Pass to Context.startActivity() or Activity.startActivityForResult() to launch an activity or get an existing activity to do something new.

Pass to Context.startService() to initiate a service or deliver new instructions to an ongoing service. Pass to Context.bindService() to establish a connection

between the calling component and a target service. It can optionally initiate the service if it's not already running.

Pass to any of the broadcast methods (such as Context.sendBroadcast(), Context.sendOrderedBroadcast(), or Context.sendStickyBroadcast()) are delivered to all interested broadcast receivers. Many kinds of broadcasts originate in system code.

65

Page 66: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Android: Broadcast Receiver

Sending a broadcast: Context.sendBroadcast(Intent intent, String receiverPermission)

Context.sendOrderedBroadcast()

Receiving broadcast: Intent registerReceiver (BroadcastReceiver receiver, IntentFilter filter)

66

Page 67: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent Resolution: Explicit

Explicit intents: component identified

67

Make sure AndroidManifest.xml announces activities to be started

Intent myIntent = new Intent(IntentController.this, TipCal.class);startActivity(myIntent);

<application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".IntentController" android:label="Intent1"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".TipCal"></activity> </application>

Page 68: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent Resolution: Implicit

Implicit intents System matches an intent object to the intent

filters of others

68

http://developer.android.com/guide/topics/intents/intents-filters.html

Page 69: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent filter

69

action

category

data

Page 70: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent Example II: Implicit

AndroidManifest.xml file for com.android.browser

70

String action = "android.intent.action.VIEW";Uri data = Uri.parse("http://www.google.com");Intent myIntent = new Intent(action, data);startActivity(myIntent);

<intent-filter>    <action android:name="android.intent.action.VIEW" />    <category android:name="android.intent.category.DEFAULT" />    <scheme android:name="http" />    <scheme android:name="https" />    <scheme android:name="file" /></intent-filter>

Page 71: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent Example II: Implicit

String action = "android.intent.action.DIAL";String phno = "tel:4326400";Uri data = Uri.parse(phno);Intent dialIntent = new Intent(action, data);startActivity(dialIntent);

Page 72: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

A Design Template: Invoker

72

String action = “com.hotelapp.ACTION_BOOK";String hotel = “hotel://name/“ + selectedHotel;Uri data = Uri.parse(hotel);Intent bookingIntent = new Intent(action, data);startActivityForResults(bookingIntent, requestCode);

Page 73: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

A Design Template: Provider

73

<activity android:name=".Booking" android:label=“Booking"> <intent-filter> <action android:name=“com.hotelapp.ACTION_BOOK" /> <data android:scheme=“hotel" android:host=“name”/> </intent-filter></activity>

For more complex data passing, please read the tutorial

Page 74: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

A Design Template: Provider

74

@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

Intent intent = getIntent(); // why am I called String action = intent.getAction(); Uri data = intent.getdata();

String hotelName = data.getPath(); // do the booking

setResult(RESULT_OK); finish();}

Page 75: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent and Broadcast: Sender

String action = "edu.yale.cs434.RUN";

Intent cs434BroadcastIntent = new Intent(action);

cs434BroadcastIntent.putExtra("message", "Wake up.");

sendBroadcast(cs434BroadcastIntent);

75

Example: IntentLaunch

Page 76: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent and Broadcast: Receiver

<receiver android:name=".CS434BroadcastReceiver" android:enabled="true">

<intent-filter>

<action android:name="edu.yale.cs434.RUN" />

</intent-filter>

</receiver>

76

Page 77: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent, Broadcast, Receiver, Notificationpublic class CS434BroadcastReceiver extends BroadcastReceiver {

public static final String CUSTOM_INTENT = "edu.yale.cs434.RUN";

// Display an alert that we've received a message.

@Override

public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals(CUSTOM_INTENT)) {

String message = (String)intent.getExtras().get("message");

CharSequence text = "Got intent " + CUSTOM_INTENT + " with " + message;

int duration = Toast.LENGTH_SHORT;

Toast mToast = Toast.makeText(context, text, duration);

mToast.show();

} // end of if

} // end of onReceive

}

77

Page 78: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Recap: Do not Block

78

ANRs (Application not responding) happen when Main thread (“event”/UI) does

not respond to input in 5 sec A broadcast receiver does

not finish in 10 sec 5-10 sec is absolute upper

bound

Page 79: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Recap: Do not Block

Numbers (Nexus One) ~5-25 ms – uncached flash reading a byte ~5-200+(!) ms – uncached flash writing tiny amount 100-200 ms – human perception of slow action 108/350/500/800 ms – ping over 3G. varies! ~1-6+ seconds – TCP setup + HTTP fetch of 6k over 3G

Rules Notify users Use background processing Example: LaunchThread Example: SimplyService

79

Page 80: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Background Processing using a Thread

Problem: Background thread and UI thread are running

concurrently and may have race conditions if they modify simultaneously

Solution: Android Handler Use Handler to send and process Message and

Runnable objects associated with a thread's MessageQueue.

80

Page 81: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Android Handler

Each Handler instance is associated with a single thread and that thread's message queue.

A handler is bound to the thread / message queue of the thread that is creating it from that point on, it will deliver messages

and runnables to that message queue and execute them as they come out of the message queue.

81

Page 82: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Using Handler

There are two main uses for a Handler: to schedule messages and runnables to be

executed as some point in the future; and to enqueue an action to be performed on a

different thread than your own.

82

Page 83: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Handler

public class MyActivity extends Activity {

    [ . . . ]    // Need handler for callbacks to the UI thread    final Handler mHandler = new Handler();

    // Create runnable for posting    final Runnable mUpdateResults = new Runnable() {        public void run() {            updateResultsInUi();        }    };

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);

        [ . . . ]    }

83

Page 84: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Handler

    protected void startLongRunningOperation() {

        // Fire off a thread to do some work that we shouldn't do directly in the UI thread        Thread t = new Thread() {            public void run() {                mResults = doSomethingExpensive();                mHandler.post(mUpdateResults);            }        };        t.start();    }

    private void updateResultsInUi() {

        // Back in the UI thread -- update our UI elements based on the data in mResults        [ . . . ]    }}

84

Page 85: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Examples

See BackgroundTimer

See HandleMessage

85

Page 86: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Tools

AsyncTask

IntentService

86

Page 87: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Tools: AsyncTask

87

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { // on some background thread 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)); } return totalSize; } protected void onProgressUpdate(Integer... progress) { // on UI thread! setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { // on UI thread! showDialog("Downloaded " + result + " bytes"); }}

new DownloadFilesTask().execute(url1, url2, url3); // call from UI thread!

See GoogleSearch

Page 88: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Does Background Solve All Issues?

88

Page 89: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Example: Accessing Data in Cloud

A typical setting is that a device accesses data in the cloud, e.g., background sync

Challenge: How do you keep data on a device fresh?

89

Page 90: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Polling

Simple to implement Device periodically asks server for new

data Appropriate for content that changes

constantly Stock Quotes, News Headlines

90

Page 91: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Impact of Polling on Battery

Baseline: ~5-8 mA Network: ~180-200 mA

Tx more expensive than Rx Assume radio stays on for 10 sec.

Energy per poll: ~0.50 mAh 5 min frequency: ~144 mAh / day

Droid 2 total battery: 1400 mAh

91Source: Android development team at Google

Page 92: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Solution: Push

Google Contacts, Calendar, Gmail, etc., use push sync

A single persistent connection from device to Google

Android Cloud to Device Messaging (C2DM) to make it a public service

92

Page 93: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

C2DM Overview

Uses existing connection for Google services

Your servers send lightweight “data” messages to apps

Tell app new data available Intent broadcast wakes up app App supplies UI, e.g., Notification, if/as

necessary

93

Page 94: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

C2DM Flow

Enabling cloud to device messaging App (on device) registers with Google, gets

registration ID App sends registration ID to its App Server

Per message App Server sends (authenticated) message to

Google Google sends message to device

Disabling cloud to device messaging App can unregister ID, e.g., when user no

longer wants push94

Page 95: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

C2DM

95

Page 96: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Android Code: Registration to C2DM// Use the Intent API to get a registration ID

// Registration ID is compartmentalized per app/device

Intent regIntent = new

Intent(“com.google.android.c2dm.intent.REGISTER”);

// Identify your app

regIntent.putExtra(“app”,

PendingIntent.getBroadcast(this, 0, new Intent(), 0);

// Identify role account server will use to send

regIntent.putExtra(“sender”, emailOfSender);

// Start the registration process

startService(regIntent);

96

Page 97: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Receiving Registration ID

97

// Registration ID received via an Intent

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

if (“…REGISTRATION”.equals(action)) {

handleRegistration(context, intent);

} }

private void handleRegistration(Context context, Intent intent){

String id = intent.getExtra(“registration_id”);

if ((intent.getExtra(“error”) != null) {

// Registration failed. Try again later, with backoff.

} else if (id != null) {

// Send the registration ID to the app’s server.

// Be sure to do this in a separate thread.

} }

Page 98: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Receiving Registration ID

App receives the ID as an Intent com.google.android.c2dm.intent.REGISTRATIO

N App should send this ID to its server Service may issue new registration ID at

any time App will receive REGISTRATION Intent

broadcast App must update server with new ID

98

Page 99: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Android: Content Provider

Each provider can expose its data as a simple table on a database model

Each content provider exposes a public URI that uniquely identifies its data set:

android.provider.Contacts.Phones.CONTENT_URI android.provider.Contacts.Photos.CONTENT_URI android.provider.CallLog.Calls.CONTENT_URI android.provider.Calendar.CONTENT_URI

99

Page 100: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Intent and Content Provider private void pickContact() {

    // Create an intent to "pick" a contact, as defined by the content provider URI    Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);    startActivityForResult(intent, PICK_CONTACT_REQUEST);}

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    // If the request went well (OK) and the request was PICK_CONTACT_REQUEST    if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {        // Perform a query to the contact's content provider for the contact's name        Cursor cursor = getContentResolver().query(data.getData(),        new String[] {Contacts.DISPLAY_NAME}, null, null, null);        if (cursor.moveToFirst()) { // True if the cursor is not empty            int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);            String name = cursor.getString(columnIndex);            // Do something with the selected contact's name...        }    }}

100

Page 101: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

101

Windows .NET Compact Framework Similar to J2ME Scales down a popular programming environment to ease

learning the .NET CF is a subset of the full .NET framework with some additions designed for resource constrained devices 1,400 classes for .NET CF vs. 8,000 for full 27 UI controls for .NET CF vs. 52 for full 1.5 MB for .NET CF vs. 30 MB for full

Uses versioning to avoid using lowest common denominator pocket PC pocket PC phone version smart phone version

Uses virtual machines to mask device heterogeneity programming languages compile to MSIL

• MSIL is JIT compiled on the device• MSIL code is smaller than native executables• MSIL allows your code to be processor independent

Page 102: 1 Mobile Software Development Framework 10/2/2012 Y. Richard Yang.

Android

Linux kernel as foundation Java based framework (J2SE not J2ME)

Dalvik Virtual machine Nice features

Touch screen, accelerometer, compass, microphone, camera, GPS,

GSM, EDGE, and 3G networks, WiFi, Bluetooth, Near field communications

Media, SQLite, WebKit, SSL Location-based service, map (Google API)

102