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

Slides:



Advertisements
Similar presentations
Android Application Development A Tutorial Driven Course.
Advertisements

MIDP Mobile Information Device Profile Johnny Yau CIS 642 Prof. Insup Lee.
1 Mobile Software Development Framework: TinyOS, J2ME 10/2/2012 Y. Richard Yang.
Android architecture overview
J2ME 25 July Overview  What is J2ME?  The CLDC and CDC configurations  MIDP and MIDlets  Development Tools  Demonstrations.
Writing Your First MIDlet Running JAVA on a Cell Phone Jon A. Batcheller January 27, 2004.
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
UNDERSTANDING JAVA APIS FOR MOBILE DEVICES v0.01.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
Developing an Application with J2ME Technology Scott Palmer, Nat Panchee, Judy Sullivan, Karen Thabet, Sten Westgard.
PDA Programming Using J2ME Presenter :涂俊凱 Date : 2003/4/8.
Mobile Application Development
Cosc 4730 Phone Programming in Java An Introduction.
Java 2 Platform, Micro Edition (J2ME) By Xiaorong Wang.
Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department.
1 Android: Event Handler Blocking, Android Inter-Thread, Process Communications 10/11/2012 Y. Richard Yang.
1 Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources, Listener 10/9/2012 Y. Richard Yang.
Android Introduction Platform Overview.
Intro to Android Programming George Nychis Srinivasan Seshan.
About me Yichuan Wang Android Basics Credit goes to Google and UMBC.
1 Mobile Software Development Framework 4/14/2009 Richard Yang.
© Keren Kalif Intro to Android Development Written by Keren Kalif, Edited by Liron Blecher Contains slides from Google I/O presentation.
@2011 Mihail L. Sichitiu1 Android Introduction Platform Overview.
Michael Brockway Advanced Applications Development in Java J2ME -- Introduction l Introduction / Overview l Java 2 Micro Edition n CLDC n MIDP l Examples.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 11 J2ME and MIDlets Rob Pooley
1 OFDM, Mobile Software Development Framework 9/27/2012 Y. Richard Yang.
1 Mobile Software Development Framework: Android 2/23/2011 Y. Richard Yang.
ANDROID Presented By Mastan Vali.SK. © artesis 2008 | 2 1. Introduction 2. Platform 3. Software development 4. Advantages Main topics.
Computer Science Wi-Fi App using J2ME and MVC Architecture Advisor : Dr. Chung-E Wang Department of Computer Science Sacramento State University Date:
DUE Hello World on the Android Platform.
CS378 - Mobile Computing Intents.
1 Mobile Software Development Framework: Android 2/28/2011 Y. Richard Yang.
J2ME Presented by May Sayed & Menna Hawash. Outline Introduction “Java Technology” Introduction “What is J2ME?” J2ME Architecture J2ME Core Concepts 
1Basics of J2ME. 2 Objectives –Understand the different java API’s and how the mobile edition API’s fit in –Understand what a mobile configuration and.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 13 lcdui and OXO Rob Pooley
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
Dhanshree Nimje Smita Khartad
System Architecture Directions for Networked Sensors Jason Hill, Robert Szewczyk, Alec Woo, Seth Hollar, David Culler, Kris Pister Presented by Yang Zhao.
ANDROID L. Grewe Components  Java Standard Development Kit (JDK) (download) (latest version)  AndroidStudio.
1 Mobile Software Development Framework: Android Inter- Thread, Process Communications 10/11/2012 Y. Richard Yang.
TinyOS Sandeep Gupta. Operating System (OS) What is an OS? Main functions  Process management  Memory management  Resource management Traditional OSs.
1 Mobile Software Development Framework: IOS 10/2/2012 Y. Richard Yang.
1 Introduction to J2ME Outline MIDP Building J2ME Apps- Tool J2ME Wireless Toolkit Demo MIDlet Programming -- MIDlet Transition States -- Midlet Skeleton.
Lecture 2: Android Concepts
1 Android Workshop Platform Overview. 2 What is Android?  Android is a software stack for mobile devices that includes an operating system, middleware.
Intents and Broadcast Receivers Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution.
 This work confers an application which makes possible to use a Bluetooth enabled mobile phone to remote control home appliances such electric fan, LEDs.
The Ingredients of Android Applications. A simple application in a process In a classical programming environment, the OS would load the program code.
Advance Computer Programming Market for Java ME The Java ME Platform – Java 2 Micro Edition (J2ME) combines a resource- constrained JVM and a set of Java.
1 Mobile Application Development Framework 4/16/2009 Richard Yang.
CS371m - Mobile Computing Intents 1. Allow us to use applications and components that are already part of Android System – start activities – start services.
The Java Platform Micro Edition Java ME
CS434/534: Topics in Networked (Networking) Systems WSN/Mobile Systems Yang (Richard) Yang Computer Science Department Yale University 208A Watson
Lecture 2: Android Concepts
Android Application Development 1 6 May 2018
Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources, Handler/ASyncTask 10/9/2012 Y. Richard Yang.
ITEC535 – Mobile Programming
Mobile Software Development Framework: TinyOS, J2ME
Mobile Software Development Framework
CMPE419 Mobile Application Development
By Jeff Heaton An Overview of J2ME By Jeff Heaton
Mobile Software Development Framework: Android
Mobile Software Development Framework: Android
Application Development A Tutorial Driven Course
Android Network Layer; Location Management
Activities and Intents
Java for Mobile Devices
Lecture 2: Android Concepts
CMPE419 Mobile Application Development
Presentation transcript:

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

2 Admin. r Homework 2 r Start to think about project

3 Recap: OFDM r Basic: use multiple subcarriers to reduce symbol rate per carrier r 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 r Key idea 2: iFFT as an efficient algorithm for modulation on multiple subcarriers r Idea 3: cyclic prefix (guard interval)

4 Recap: Summary of Wireless PHY

5 Recap: GNURadio r A software development toolkit that provides signal processing blocks to implement software-defined radio systems. r Some key ideas m Hybrid software system (Python/C++) m Composite pattern to build a hierarchy of blocks m Internal scheduler to orchestrate data flows among blocks m Define gr_block as a reusable base so that defining a new block typically means only rewrite general_work and forecast

6 Recap: TinyOS r A free and open source component based operating system and platform targeting wireless sensor networks (WSNs) r Some design features m TinyOS: Generate customized OS + application: support one app at a time but flexible reprogramming

7 TinyOS: Software Concepts r A TinyOS consists of one or more components/modules linked together m software components motivated by hardware component r Each component specifies: m it provides some interfaces allows other components to control it m also uses some interfaces control other components

8 Interface r An interface declares m a set of functions called commands that provider must implement m 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 events I1 I2 C provides I3

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); }

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

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 events I1 I2 C provides I3

12 Module: Implementation r Define m commands and event handlers m frame (storage) statically allocated, fixed size to know memory requirement and avoid overhead of dynamic allocation r See SenseTaskM.nc Component Internal State Internal Tasks CommandsEvents

13 Linking Components Two types of components: m modules: individual components m configurations : assemble components together, connecting interfaces (objects) used by components to interfaces (objects) provided by others See SenseTask.nc

14 TinyOS Execution Model A uses interfaces I1 and I2 B provides I1 C provides I2 commands events commands events C provides I3

15 TinyOS Execution Model r Concurrency model: only two threads m long running tasks that can be interrupted by hardware event handlers r Each task is atomic with respect to other tasks m run to completion, but can be preempted by events m the task scheduler is a simple FIFO scheduler r Tasks perform the primary computation work m commands and event handlers post tasks m call lower level commands m signal higher level events m schedule other tasks within a component

16 Running tinyOS Program r make mica r ncc -o main.exe -target=mica SenseTask.nc r avr-objcopy --output-target=srec main.exe main.srec r Use uisp to install

17 A More Complete Sample Application r Sensor network monitoring m monitor temperature and light conditions m periodically transmit measurements to a base station m sensors can forward data for other sensors that are out of range of the base station m dynamically determine the correct routing topology for the network

18 Internal Component Graph RFM Radio byte Radio Packet UART UART Packet I2C Temp Light Active Messages Clocks bit byte packet Ad hoc Routing Application application HW SW

19 Message Send Transition r Total propagation delay up the 5 layer radio communication stack is about 80 instructions Timing diagram of event propagation

20 Evaluation: Storage Component NameCode Size (bytes) Data Size (bytes) Routing AM_dispatch AM_temperature AM_light AM RADIO_packet RADIO_byte RFM Light Temp UART UART_packet I2C Processor_init TinyOS scheduler C runtime Total  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

21 Evaluation: Timing OperationsCost (cycles) Time (µs) Normalized to byte copy Byte copy821 Post an Event Call a Command Post a task to scheduler Context switch overhead Interrupt (hardware cost) Interrupt (software cost)

Summary: TinyOS r Components m provide commands and require callback hooks for event-driven programming r Configurations m Link components r TinyOS m an app (configuration) at a time, linking only necessary components r Two threads exec m one for event m 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; }

Discussion: Compare TinyOS/GNURadio r What are some similar software concepts? r What are some differences? 23

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

25 Java2 Micro Edition (J2ME)

26 Outline r Admin and recap r Mobile/wireless development framework m GNURadio m TinyOS m J2ME

27 Java Platforms r Java2 is divided into three platforms m J2EE (Java2 Enterprise Edition) business applications m J2SE (Java2 Standard Edition) general applications m J2ME (Java2 Micro Edition) small devices such as mobile phone, PDA, car navigation r Oracle’s claims on Java on mobile devices m

28 J2ME Basic Concepts: Versioning r To accommodate heterogeneous mobile devices, define configurations and profiles -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

29 J2ME K mem bit proc Upto 2M mem 32 bit proc

30 Example J2ME Configurations r Connected Limited Device Configuration (CLDC) m 160 KB to 512 KB of total memory available m 16-bit or 32-bit processor m low power consumption and often operating with battery power m connectivity with limited bandwidth m examples: cell phones, certain PDAs r Connected Device Configuration (CDC) m 2 MB or more memory for Java platform m 32-bit processor m high bandwidth network connection, most often using TCP/IP m examples: set-top boxes, certain PDAs

31 CLDC Available Packages r java.lang r java.util r java.io r javax.microedition.io

32 CLDC Classes r Boolean r Byte r Character r Class r Integer r Long r Math r Object r Runnable r Runtime r Short r String r StringBuffer r System r Thread r Throwable r Calendar r Date r Enumeration r Hashtable r Random r Stack r TimeZone r Vector r ByteArrayOutputStream r ByteArrayInputStream r DataOuput r DataInput r DataInputStream r DataOutputStream r InputStream r InputStreamReader r OutputStream r OutputStreamWriter r PrintStream r Reader r Writer java.lang java.util java.io

33 Example J2ME Profiles r Mobile Information Device Profile (MIDP) m GUI, multimedia and game functionality, end-to-end security, and greater networked connectivity m mobile phones and entry level PDAs r Foundation Profile m set of Java APIs that support resource-constrained devices without a standards-based GUI system r Personal Profile m Full set of AWT APIs, including support for applets and Xlets m CDC + Foundation Profile + Personal Profile for high-end PDA r …

34 Mobile Phone Framework

35 MIDP Hardware r Memory (added to CLDC memory) m 128 KB non-volatile for MIDP components m 8 KB non-volatile for application persistent data m 32 KB volatile for KVM r Display m screen 96x54 m display depth 1-bit m pixel shape (aspect ratio) 1:1

36 MIDP Hardware r Input (one or more) m one-handed keyboard (ITU-T phone keypad) m two-handed keyboard (QWERTY keyboard) m or touch screen r Networking m two-way m wireless m possibly intermittent m limited bandwidth

37 MIDP Packages r java.io r java.lang r java.util r javax.microedition.io r javax.microedition.lcdui r javax.microedition.rms r javax.microedition.midlet r javax.microedition.lcdui.game r javax.microedition.media r javax.microedition.media.control r javax.microedition.pki addition in version 2.0 version 1.0

38 MIDP Technology Stack Mobile Information Device Profile KVM CLDC = KVM + J2ME Core APIs in this example DSP chip (e.g., ARM) J2ME core APIs Your MIDlet Yellow Pages, train schedules and ticketing, games… UI, HTTP networking... Threads, no Floats… 32-bit RISC, 256K ROM, 256K Flash, 64K RAM

MIDlet m GUI based m 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( ) 39

40 MIDlet r An MIDP application is called a MIDlet m similar to the J2SE applet r A MIDlet moves from state to state in the lifecycle, as indicated m start – acquire resources and start executing m pause – release resources and become quiescent (wait) m destroy – release all resources, destroy threads, and end all activity PauseActiveDestroyed startApp destroyApp pauseApp destroyApp

MIDP Visual Display r 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( ) 41

MIDP Visual Display r Displayable m Canvas GameCanvas m Screen Alert, List, TextBox, Form r Form can contain multiple form items for organization m Labels, Image Items, String Items, Text Fields, Date Fields, Gauges, Choice Groups 42

MIDP: User Interaction  Displayable objects can declare commands and declare a command listener: m addCommand(Command cmd) m addCommandListener() r Command(,, ) m Type: BACK, CANCEL, EXIT, HELP, ITEM, OK, SCREEN, and STOP 43

44 HelloWorldMIDlet.java import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class HelloWorldMIDlet extends MIDlet implements 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(); }

MIDP: Persistent State r Record store defined in javax.microedition.rms r Record store identified by name: m static String[] listRecordStores(); m recordStore = RecordStore.openRecordStore("scores", true); m recordId = addRecord(byte[] data, int offset, int numBytes); m getRecord(int recordId); 45

46 Summary : J2ME r Scale down a popular programming environment to ease learning r Use virtual machines to mask device heterogeneity r Use configuration/profiling to handle device heterogeneity and avoid using lowest common denominator r MIDLet to manage app life cycle r Displayable to visual display, commands and provides command listener r Introduce persistent record store

Discussion on J2ME r What designs of J2ME do you like and hence expect newer frameworks (e.g., IOS, Android) may have too? r What features do you think are missing in J2ME? 47

48 Outline r Admin and recap r Mobile/wireless development framework m GNURadio m TinyOS m J2ME m Android

Android r A mobile OS, application framework, and a set of applications m 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 m Application development framework Based on Java (J2SE not J2ME) Dalvik Virtual Machine 49

Android Architecture 50

Poking Android OS r See w/index.html w/index.html r Android SDK Manager (android) to start a simulator r Android debug bridge (adb) can connect to an Android device and start a shell on the device

Application Framework (Android): Key Concepts r Activity r View r External resources r Service r Intercommunications 52 App Communication among apps: - Intent - broadcast - data provider

Activity r A single, focused thing that the user can do. r Interaction with users: creating a window to place UI views r full-screen windows, floating windows, embedded inside of another activity

r Android Activity Life cycle 54

View r A view component is a building block for user interface components. r Widget Toolbox m TextView, EditText, Button, Form, TimePicker… m ListView m Layout Positions of controls LinearLayout, Relativelayout

View by XML r Layout of visual interface r Java Code m Initialize m Access TextView myTextView = (TextView)findViewById(R.id.myTextVie w); <LinearLayout xmlns:android=” /apk/res/android” android:orientation=”vertical” android:layout_width=”fill_parent” android:layout_height=”fill_parent”> <TextView android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”Hello World, HelloWorld” public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } main.xml

User Interaction Event r onKeyDown. onKeyUp r onTrackBallEvent r 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) {….}}

Example: TipCal 58

Application Framework (Android): Key Concepts r Activity and view m Visible screen for user interaction r External resources 59

External Resources 60

Application Framework (Android): Key Concepts r Activity and view m Visible screen for user interaction r External resources r Service 61

Service: Working in Background r A basic function of Android Service: m 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). m The system to schedule work for the service, to be run until the service or someone else explicitly stop it. m NO GUI, higher priority than inactive Activities r Note m 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. m 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).

Application and Component Glues r Intent m An intent is an abstract description of an operation to be performed. m To invoke operations from your own or others m Can pass data back and forth between app. r Intent Filter m Register Activities, Services, and Broadcast Receivers as being capable of performing an action on a particular kind of data.

Intent Description m m Action m Data m Category, e.g., LAUNCHER 64

Intent Usage r Pass to Context.startActivity() or Activity.startActivityForResult() to launch an activity or get an existing activity to do something new.Context.startActivity() Activity.startActivityForResult() r Pass to Context.startService() to initiate a service or deliver new instructions to an ongoing service.Context.startService() m 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.Context.bindService() r 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. Context.sendBroadcast()Context.sendOrderedBroadcast() Context.sendStickyBroadcast() 65

Android: Broadcast Receiver r Sending a broadcast: m Context.sendBroadcast(Intent intent, String receiverPermission) m Context.sendOrderedBroadcast() r Receiving broadcast: m Intent registerReceiver (BroadcastReceiver receiver, IntentFilter filter) 66

Intent Resolution: Explicit r Explicit intents: component identified 67 r Make sure AndroidManifest.xml announces activities to be started Intent myIntent = new Intent(IntentController.this, TipCal.class); startActivity(myIntent); <activity android:name=".IntentController" android:label="Intent1">

Intent Resolution: Implicit r Implicit intents m System matches an intent object to the intent filters of others 68

Intent filter 69 action category data

Intent Example II: Implicit r AndroidManifest.xml file for com.android.browser 70 String action = "android.intent.action.VIEW"; Uri data = Uri.parse(" Intent myIntent = new Intent(action, data); startActivity(myIntent);

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

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);

A Design Template: Provider 73 r For more complex data passing, please read the tutorial

A Design Template: Provider public 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(); }

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

Intent and Broadcast: Receiver 76

Intent, Broadcast, Receiver, Notification public class CS434BroadcastReceiver extends BroadcastReceiver { public static final String CUSTOM_INTENT = "edu.yale.cs434.RUN"; // Display an alert that we've received a 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

Recap: Do not Block 78 r ANRs (Application not responding) happen when m Main thread (“event”/UI) does not respond to input in 5 sec m A broadcast receiver does not finish in 10 sec r 5-10 sec is absolute upper bound

Recap: Do not Block r Numbers (Nexus One) m ~5-25 ms – uncached flash reading a byte m ~5-200+(!) ms – uncached flash writing tiny amount m ms – human perception of slow action m 108/350/500/800 ms – ping over 3G. varies! m ~1-6+ seconds – TCP setup + HTTP fetch of 6k over 3G r Rules m Notify users m Use background processing  Example: LaunchThread m Example: SimplyService 79

Background Processing using a Thread r Problem: m Background thread and UI thread are running concurrently and may have race conditions if they modify simultaneously r Solution: Android Handler m Use Handler to send and process Message and Runnable objects associated with a thread's MessageQueue.MessageMessageQueue 80

Android Handler r Each Handler instance is associated with a single thread and that thread's message queue. r A handler is bound to the thread / message queue of the thread that is creating it m 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

Using Handler r There are two main uses for a Handler: m to schedule messages and runnables to be executed as some point in the future; and m to enqueue an action to be performed on a different thread than your own. 82

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(); } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); [... ] } 83

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

Examples r See BackgroundTimer r See HandleMessage 85

Tools r AsyncTask r IntentService 86

Tools: AsyncTask 87 private class DownloadFilesTask extends AsyncTask { 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

Does Background Solve All Issues? 88

Example: Accessing Data in Cloud r A typical setting is that a device accesses data in the cloud, e.g., m background sync r Challenge: How do you keep data on a device fresh? 89

Polling r Simple to implement r Device periodically asks server for new data r Appropriate for content that changes constantly m Stock Quotes, News Headlines 90

Impact of Polling on Battery r Baseline: ~5-8 mA r Network: ~ mA m Tx more expensive than Rx r Assume radio stays on for 10 sec. m Energy per poll: ~0.50 mAh m 5 min frequency: ~144 mAh / day r Droid 2 total battery: 1400 mAh 91 Source: Android development team at Google

Solution: Push r Google Contacts, Calendar, Gmail, etc., use push sync r A single persistent connection from device to Google r Android Cloud to Device Messaging (C2DM) to make it a public service 92

C2DM Overview r Uses existing connection for Google services r Your servers send lightweight “data” messages to apps r Tell app new data available r Intent broadcast wakes up app r App supplies UI, e.g., Notification, if/as necessary 93

C2DM Flow r Enabling cloud to device messaging m App (on device) registers with Google, gets registration ID m App sends registration ID to its App Server r Per message m App Server sends (authenticated) message to Google m Google sends message to device r Disabling cloud to device messaging m App can unregister ID, e.g., when user no longer wants push 94

C2DM 95

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”, OfSender); // Start the registration process startService(regIntent); 96

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. }

Receiving Registration ID r App receives the ID as an Intent m com.google.android.c2dm.intent.REGISTRATION r App should send this ID to its server r Service may issue new registration ID at any time r App will receive REGISTRATION Intent broadcast r App must update server with new ID 98

Android: Content Provider r Each provider can expose its data as a simple table on a database model r Each content provider exposes a public URI that uniquely identifies its data set: m android.provider.Contacts.Phones.CONTENT_URI android.provider.Contacts.Photos.CONTENT_URI android.provider.CallLog.Calls.CONTENT_URI android.provider.Calendar.CONTENT_URI 99

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); protected 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

101 Windows.NET Compact Framework r Similar to J2ME r Scales down a popular programming environment to ease learning m the.NET CF is a subset of the full.NET framework with some additions m designed for resource constrained devices m 1,400 classes for.NET CF vs. 8,000 for full m 27 UI controls for.NET CF vs. 52 for full m 1.5 MB for.NET CF vs. 30 MB for full r Uses versioning to avoid using lowest common denominator m pocket PC m pocket PC phone version m smart phone version r Uses virtual machines to mask device heterogeneity m 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

Android r Linux kernel as foundation r Java based framework (J2SE not J2ME) m Dalvik Virtual machine r Nice features m Touch screen, accelerometer, compass, microphone, camera, GPS, m GSM, EDGE, and 3G networks, WiFi, Bluetooth, Near field communications m Media, SQLite, WebKit, SSL m Location-based service, map (Google API) 102