workshop - stanislav rost's productions
TRANSCRIPT
A Practical WorkshopA Practical Workshop
Stanislav RostCSAIL, MITCSAIL, MIT
INTRODUCTIONWorkshop
INTRODUCTION
About Me
• NAME: Stan Rost• OCCUPATION: Ph.D. Student, Computer Science, MIT
• RESEARCH GROUP: Networks and Mobile Systems (NMS)y
• INTERESTS: Mobile applications, sensor networks, server scalability, P&D
A• ANDROID EXPERIENCE: Principal developer of a social network app, RE:Public ‐‐
Top 100 out of 1788 submissions to Google’s Android p 7 gDesign Challenge; 30+ KLoC, pervasive use of all platform features
RE:Public v1.0
About Me
• NAME: Stan Rost• OCCUPATION: Ph.D. Student, Computer Science, MIT
• RESEARCH GROUP: Networks and Mobile Systems (NMS)
• INTERESTS: mobile applications, sensor networks, server scalability , P&D
• ANDROID EXPERIENCE:ANDROID EXPERIENCE: Principal developer of a social network app, RE:Public ‐‐
Top 100 out of 1788 submissions to Google’s Android Design Challenge; 30+ KLoC pervasive use of all platform featuresChallenge; 30+ KLoC, pervasive use of all platform features
Currently interested in projects on MIDs, phonesW t t l b t th h t QRDC ll b t Want to learn about the research at QRDC, collaborate
Workshop Plan
1• Lecture: platform overview, top‐level components
1p , p p
• Lab: SDK, project development, first sample app
• Lecture: lifecycles, GUI and layout• Lab: first full‐featured application
2
• Lecture: sensors, GPS and maps• Lab: guided development of applications3 g p pp
Pre‐Requisites
RequiredRequired Familiarity with Java Curiosity about mobile software developmenty p Attention to workshop presentations
Preferable Experience with the
Eclipse development environmentEclipse development environment
Disclaimer
Opinions offered in this workshop are my ownOpinions offered in this workshop are my own
Not affiliated with Google
Quanta is “Terra Incognita”Quanta is Terra Incognita
PLATFORM OVERVIEWAndroid
PLATFORM OVERVIEW
Evolution
July 2005 Google acquires the Android company
November 2007 Google announces Android platform,
O d llOpen Handset Alliance
January‐August 2008A d id D i Ch ll t t Android Design Challenge contest
September, October 2008 Android 0 Android 1.0
HTC Dream / T‐Mobile G1
May 2009
Imagesource:richd.com
May 2009 Android 1.5 “Cupcake” released
What is Android?
Android uses the Linux kernel, but is not Linux Tasty bits of kernel: y
threading, MM, networking stack, device drivers BSD‐derived LibC, tuned for embedded devices (200KB)
h ll d d k No shell, X window manager, desktop manager, etc.
Android uses Java but is not a Java platformAndroid uses Java, but is not a Java platform No support for Swing, some other libraries Compiles Java syntax into Dalvik bytecode Compiles Java syntax into Dalvik bytecode Every application runs in its own process, own Dalvik VM Dalvik is register‐based, optimized for small RAM footprintg , p p System hardware is exposed to the VM via Java libraries
Platform Components & Interaction
Included Software Libraries & APIs LibWebCore (WebKit):
modern browser engine + SquirrelFish for JavaScriptSSL d ARM ti i d t SSL and ARM‐optimized crypto
PacketVIDEO’s OpenCore: MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, etc.4, 4, 3, , , , ,
SGL: graphics engine OpenGL ES 1.0 implementation (including in software) SurfaceManager: compositing of layers in display subsys FreeType: bitmap and vector font SQLite: lightweight relational database Google Maps and geocoder
A GPS via LocationManager A‐GPS via LocationManager Nuance Speech Recognition Engine
Supported Hardware
SoC with ARM926 or higher (e.g. ARM11) Must have Linux >2.6.23 running on target with 3 g g
Thumb& MMU & EABI support
SoCmust provide and Linux kernel must support Display frame buffer + double buffering Serial console
K b d Keyboard RTC Storage more than 64MB Storage, more than 64MB SDRAM, more than 32MB USB (optional)( p )
Comparison to Other Mobile PlatformsSources:• Apple Inc.• StrategyAnalyticsy
Feature iPhone 3.0 Android 1.5
Users> 17 million
(19‐24 by end of 2010)> 1 million
(9 ‐ 20 million by 2010)
Apps > 10,000 > 500pp , 5
Distinct features
Push‐based processingFast GPS convergenceProprietary everything
Background processingPhysical keyboardNotification bar
featuresMulti‐touch screenProximity sensor
Home screen widgetsSD card
QUANTA & ANDROID?Entertaining the possibilities
QUANTA & ANDROID?
Three Markets for Android Hardware
Mobile phones A strong, but shy contender g y
Netbooks Hard to see the value proposition relative to x86 netbooks
Hybrid MIDs Tablets / digital frames / readers / home automation / VoIP
Routon 760/730 Nimble Touch Revolution
Considering the Android Platform
•Well‐designed, modern, fast
k d f hi h d
•Who will market the device?
h h d i h b•Makes good use of high‐end phone hardware
•Open source (mostly) open
•The hardware is cheap, but not the cheapest
•Some fragmentation expected•Open‐source (mostly), open
•Very low cost of adoption
•Some fragmentation expected
•Some big‐name competitors already in the market
•Google maintains the ecosystem
already in the market
•Google’s goals, financial incentives unknowny
Ideas for Android Device Makers
Novel hardware features o e a d a e eatu esandsoftware projects that use them in exciting ways develop / sponsor / contribute software
A smart phone or a MIDis an ideal user agent for interfacing with
h ki d f d imany other kinds of devices browsing output of / controlling other devices
Exciting Opportunities
Ultra low‐power, near‐field communication 1000 uses for ad‐hoc protocols; p
would love a ZigBee chip or secondary WiFi
Open peripheral interface HW interface , software stack to work with many sensors,
actuators
Pervasive power management supportPervasive power management support Hardware‐assisted scheduling and “server push”
communicationscommunications
User‐area networks Telephones and MIDs should be central in an ecosystem of p y
wireless sensors, automation devices, proximity beacons
APPLICATION FUNDAMENTALSThe practical portion of the workshop starts here
APPLICATION FUNDAMENTALS
Application Fundamentals Plan
Top Level Components1 Top-Level Components1
Memory Management2
Security3
Concurrency4
Inter-Component Communication5
Top‐Level Application Components
Activity A window of UI elements ; no other component has big UIp g
Service Runs in the background “indefinitely” Can communicate with other components via RPC
BroadcastReceiver Filters system‐wide message broadcasts reacts to some Filters system‐wide message broadcasts, reacts to some
ContentProvider Exposes application’s persistent data to other applications
Activity
A class extending Activity Overrides some methods
Contains Window , UI layout & elements Data structures and data Callbacks for UI & other events
Life cycle Active only when on top May be destroyed at any time
Weather app extends TabActivity, provides Layouts for every tab,
manages custom ListViews
Service
A Persistent Entity Runs in the background of other g
activities, applications
T i f S iTwo primary uses of Services Can host threads that may
block, must live a long timeblock, must live a long time
Can remote procedure call from/to other components
This MP3 player is an Activityp y yBut, a Service plays the MP3 file
Broadcast Receiver
Listens to specific Intents An Intent is an “action” on
“data” (more in later slides)
Receives system‐wide Intents Registers what it listens to via
an IntentFilteran IntentFilter
Short lifespan Only one method Only one method
The Web Browser has a BroadcastReceiver for Intent(ACTION_VIEW, “http://www.google.com”)
Content Provider
Exposes some of an application’s data to other applications Data can be stored in:
fl t fil SQLit t kflat files, SQLite, network
Interface for data accessInterface for data access Apps use ContentResolvers Remote database cursors, ,
update notifications
Contacts is a ContentProvider forCo tacts s a Co te t o de ocontent://contacts/phones
Top‐Level Application Components
Activity A window of UI elements ; no other component has big UIp g
Service Runs in the background “indefinitely” Can communicate with other components via RPC
BroadcastReceiver Filters system‐wide message broadcasts reacts to some Filters system‐wide message broadcasts, reacts to some
ContentProvider Exposes application’s persistent data to other applications
Memory Management and Lifecycles
Most resources are tied to Contexts I.e. the top‐level components which allocated themp p
A component can be paused or destroyed anytime But, not before a warning callback Android provides some support for persisting state
Priority of destruction 1. Background processes in LRU order2. Services3. Foreground processes
Subject of detailed discussion in Session 2
Security and Access Scoping
Private storage A flash chip soldered to the boardp On HTC Dream, 32MB with 10MB available to applications Android uses Linux permissions to prevent runtime access
bto its binaries
Application access scopingApplication access scoping Applications are given private‐access directories Applications cannot access other applications’ private Applications cannot access other applications private
storage Android Market has additional option to encrypt
applications
Concurrency and Multi‐Threading
The top‐level Activity runs in the main application process If you don’t create Threads, the execution is serial*
With the exception*
Why Threads are necessary Android scheduler will offer to KILL any app whose
llb k h d k h d
With the exceptionof some parts of
RPCscallback method takes more than X seconds
Good candidates are network I/O, long calculations
Threads quirksTh d t UI t Threads cannot access UI components
Threads must die with Activity that started them
Inter‐Component Communication
Intents Passive messages that initiate actionsg May include extra data as key‐value pairs
Activity results An Activity can start another Activity for result
Remote procedure calls Used between Activities and Services Used between Activities and Services
ContentProvider queriesq A managed way to access data, including another app’s
Intents
Data structures telling Android to run something Action – what action to perform [+ Category]p g y
(VIEW, EDIT, DIAL, MAIN, etc.) Data – what data to perform it on
(URI like content://contacts/1 )(URI like: content://contacts/1 ) Component – which class to instantiate and run
(Example: com.socialnetwork.EditProfile.class)( p ) Extras – key‐value attributes ≈ Map<String,Object>
(“id” => “12”)
Launch Intents with startActivity(…), startService( ) or broadcastIntent( )startService(…) or broadcastIntent(…)
Intent Example
...// Open the eb bro ser// Open the web browser
URI uri = Uri.parse(“http://www.google.com”);
Intent i =new Intent(Intent.ACTION_VIEW,
uri);
startActivity(i);
...
Activity Results
Activity Results: Start Another Activitypublic class FileUpload extends Activity {
…// In [Browse…] button’s OnClickListenerIntent i = new Intent(this, FileChooser.class);i.putExtra(“initialPath”, currentDirPath);startActivityForResult(i, DEFAULT_REQUEST_CODE);
…
}
Activity Results: Get Intent Arguments
public class FileChooser extends Activity {…
// In onCreate(…)String curPath = getIntent().getStringExtra(“initialPath”);
…
}
Activity Results: Return Results
public class FileChooser extends Activity {
…// In the file list’s selection handlerIntent i = new Intent();i.putExtra(“fileName”,
curFile.getAbsolutePath());setResult(DEFAULT_RESULT_CODE, i);finish();
…}
Activity Results: Process Resultspublic class FileUpload extends Activity {
…@Overridepublic void onActivityResult(int reqCode, int resCode, Intent i) {
Bundle extras = i.getExtras();String chosenFile = extras.getString(“fileName”);// Update the UI with the path of the chosen file…
} …
}
Remote Procedure Calls
A method is called locally, butexecuted remotely in another process Usually, an Activity or a BroadcastReceiver binds to
and calls a ServiceA S i ll b k ALL h ll b d i A Service can call back to ALL the remote callers bound to it
Call arguments are marshalled, queued as messages, dequeued, de‐marshalleddequeued, de marshalled
Carefully consult the documentationy Android Interface Definition Language (AIDL) IBinders, RemoteCallbackList Reuse a lot of the code from examples
ContentProvider Queries
Use a ContentResolver to communicate with the ContactProvider for a specific URI ContentResolvers manage inter‐process communication
in providing access to other application’s data
Use query(…), insert(…), update(…), delete(…) Query results are returned as Managed Cursors –
revitalize automatically when process is killed, then revived
A ContentObserver gets notifications when data is gchanged
LEARNING MORE ABOUT Teach a man to fish, and he shall never be hungry again
LEARNING MORE ABOUT ANDROID
The Documentation
http://developer.android.com/index.html OR <SDK directory>/documentation.html
API Demos
In Eclipse, add demos as a project File > Import > Existing Projects Into Space > Select Root p g j p
Directory … Choose
<SDK Directory>/platforms/android‐1.x/samples/ApiDemos
Useful Websites
Android Developers http://groups.google.com/group/android‐developersp g p g g g p p
Android Issue Tracker http://code.google.com/p/android/issues/list
Android Source Code http://android.git.kernel.org/
Community websitesA d idG Ph d id T lkA d id A d idA h iAndroidGuys Phandroid TalkAndroid AndroidAuthority
Assignment: Focused Research
Find a way to execute a Runnable task periodicallywithin the context of a running Activitythat does not involve Threads
Discover a class that can be used to run an Activity at a specific time in the future
Determine how to start a Service automatically at boot time
Submit by 14:00 to: [email protected] by 14:00 to: [email protected] [xxxxxx] in e-mail title, and your name in body
FIRST STEPS WITH THE Time to use your laptops
FIRST STEPS WITH THE ANDROID SDK
SDK: Installation, Step I
Get Java SDK http://java.sun.com/javase/downloads/index.jspp j j j p Set JAVA_HOME, add JDK’s \bin to PATH
Get Android SDK http://developer.android.com/sdk/1.5_r2/index.html Add SDK’s \bin to PATH
Get Eclipse for Java Developers http://java.sun.com/javase/downloads/index.jsp
Get the Android Plugin for Eclipse In Eclipse, Help > Software Updates > Available
Software > Add Site Software > Add Site … “http://dl‐ssl.google.com/android/eclipse/”
SDK: Installation, Step II
Set up Android SDK location with Android Plugin In Eclipse, p
Window > Preferences … > Android > SDK Location > Browse …, find your SDK directory
Create an Android Virtual Device for the emulator From command line: From command line:android list targetsandroid create avd –n MainPhone –t 2 –c 4096M
Create an Android project in Eclipse File > New > Android Project File > New… > Android Project
Android Project Directory Structure
Your packages and source files
Android Project Directory Structure
Resource file (auto-generated)
Resource compiler generates unique integer IDs in R.java
for layouts, UI elements, images and other resourcesimages and other resources
Android Project Directory Structure
The Android class library
Android Project Directory Structure
Resource Type Directory File
Images res/drawable *.png, *.jpg
Sounds res/raw *.wav,*.mp3
UI Layouts res/layout *.xmly / y
String constants res/values strings.xml
Array constants res/values arrays.xml
Android Project: Adaptive Resources
Layouts and orientations ayouts a d o e tat o sres/layout‐port/ res/layout‐land/
l li iLanguage localizationres/values‐en/ res/values‐de/ res/values‐cn/
Android Project Directory Structure
Declare top-level components, permissionsp p p
Android Project: Application Manifest
Declare your top‐level components Component receiving intent action MAIN in category p g g y
LAUNCHER starts your program
P i iPermissions <uses‐permission
android:name=“android.permission.INTERNET” />
More examples:CAMERA, ACCESS FINE LOCATION, READ CONTACTS, _ _ , _
Other application propertiespp p p
SDK: Emulator, command‐line tools
Emulation is at ARM hardware level Not emulated: camera, microphone, sensors except GPSp p Real hardware is faster
Android Debug Bridge (adb) Connects to emulator over socket Can upload, install applications,
run a simple Unix‐like shell, show console output
Dalvik Debug Monitor Service (ddms) Inspect memory allocation running processes Inspect memory allocation, running processes Drive emulated telephony, GPS sensor
SDK: Quick Notes On Debugging
In Eclipse, can run the application in “Debug Mode” Set breakpoints, inspect values, step through code Lots of bugs that occur “outside” of your code not easy to
i D b M dsee in Debug Mode
Majority of debugging is done in consoleC d li t l “ db l t” h l t t Command‐line tool “adb logcat” shows console output and trace dumps
“ddms” also shows console output, colorizes depending p , p gon severity
Use Log.d(“tag”, “…”) to output to the console. Also, ( ) ( ) tLog.e(…), Log.w(…) etc.
Summary of Session I
Slides are available for download here:http://www.mit.edu/~stanrost/quanta09/session1/
Topics coveredWhat is Android? What is Android?
Four main Android application component types Resource management in Android OS Resource management in Android OS Communication among the four main component types SDK installation and overview
Next session: Training Room B, 15:00‐16:30 Component lifecycles, GUI design
First Android Application
• Naturally, “Hello World”– Start simplep
– Add a button
– Wire the button to show a Toast
– Add another button, wire to show a Dialog• Receive Dialog response, incorporate in output