Unlocking Android Development
A tour of the Android platform, from kernel and core libraries, to APIs and software development with the SDK.
»
Unlocking Android Development
Charlie Collins
charlie.collins@gmail.com
@charliecollins
GWT in Practice - Manning Publications 2008
Unlocking Android - Manning Publications 2009
Android in Practice - Manning Publications 2010
What is Android?
"Android is a software stack for mobile devices that includes an operating system, middleware and key applications."
More than mobile really, but that's the line on http://code.google.com/android/.
In the beginning . . .
Cyberdyne Systems develops SkyNet
. . . we know where this is going, right?
Straw Poll
Who uses Java? Java "the language"?
The language matters too (along with the platform)
You need a little Java and XML experience to get started with Android
Anybody already working with Android?
Your'e gonna like Android, nice APIs (mostly)
and easy to work with. Get. Stuff. Done.
Operating System
Middleware
Runtime
Key Applications
SDK and developer tools
Big Picture (my version)
Operating System
Middleware (Libraries)
it's open source already
memory management
process management
security model
networking
drivers (and driver framework)
Who's behind Android
Kernel enhancements
IPC/Binder
Power management
Low memory killer
Logger
more
Not everything you might expect
Based on Linux
No glibc - Bionic
No Xwindows
Just what's needed - many GNU tools/utils not there (intentionally)
Small, embedded
WebKit
SQLite
OpenCore (av support)
OpenGL ES (3D)
SG L (2D and base)
FreeType
Runtime
Dalvik "clean room" VM
Based on subset of Apache Harmony (not OpenJDK - "because of GPL")
"most of the functionality" of JSE
dx tool .class into .dex
Conversion to dx happens at build time (Dalvik runs dex, not .class)
Every Android Package (APK) runs in it's own process (by default).
Every process runs it's own
instance of Dalvik VM.
"All applications are created equal."
Open Handset Alliance (65 companies)
Less expensive, better "mobile" experience
"Innovating in the open"
Fast and easy application development
http://www.openhandsetalliance.com/
The Android Open Source Project (AOSP)
Nothing to do with fables
Open Source
Meritocracy
Several OSI approved licenses
Apache 2.0 "preferred"
Kernel patches GPLv2
http://source.android.com
Key Applications
Launcher (home), contacts, calc, calendar, music, browser, etc
Google apps -- *NOT* all open source
Market, gmail, maps, navigator, talk, youtube, etc
Included with manufacturers official builds.
Some have open source alternatives.
The Market
Many apps (exact number, who cares?)
Free and paid
Google Checkout "merchant account"
$25 USD to join
Devs get 70% -- you pick price
Many countries now, not all, still adding
Do have app terms, though not drawn out approval policy
http://www.android.com/market/
android
Lifecycle
onX methods
Separate phases
May not all be called
Platform manages resources
onPause and beyond are "killable"
Here today, gone today!
Layout
XML Resource or code
Linear
Table/Grid
Relative
Layout Parameters (size/margin/padding)
Views
ViewGroup (View that has children, base for layouts)
View (UI and events, base class for widgets)
Layout - ViewGroup.LayoutParams - position, size, padding, margins
Widgets - DatePicker, TimePicker, MapView, WebView, etc
Events - Interfaces with callbacks (OnClickListener, etc)
Menus - specialized Views
Styles/Themes
units: use sp for fonts, which can scale by preference,
and dp for everything else (general, not set in stone, rule)
Performance Tips
Think differently, efficiency really matters
You don't have unlimited memory and CPU
Prefer concrete over interface (ArrayList over List, etc -- up to 2x faster)
Prefer static methods over virtual (don't access members, make it static)
Don't use getters/setters (field lookups much faster)
Declare constants final (VM can access them faster)
Avoid enums (result in large files, comparatively)
Avoid floats (no hardware co-processor, done in software)
All of these guidlines have exceptions (weigh perf vs usability)
Tools
ADB
DDMS
AAPT
layoutopt
hierarchyviewer
UI exerciser monkey
Eclipse ADT
9-patch tool
more . . .
Introduction
Platform Overview
"Market" Conditions
Google Code Search
Documentation itself (gotten pretty good)
API level in JavaDoc
Practical Tips
Key Framework Components
Hello World
First Project
Eclipse
*or* "android" command line tool
AndroidManifest.xml
Activity class
layout.xml "layout" resource
strings.xml "string" resource
R.java (generated)
Task
A task is a collection of activities the user
sees as an "application."
Root activity starts task
Task stack ("recent" long press home )
Activity
Roughly a "screen"
Creates a window where you place Views
Extends (and therefore provides) Context
Activity stack
Back key (end stack at home)
Lifecycle
Started stopped and resumed at will
Make use of Intents
Can be end point for Intents
With Intents can be thought of as "embedded SOA" (well, maybe a bit of a stretch)
Declared and registered in Manifest
ContentProvider
BroadcastReceiver
Intent
Activities, Services, and BroadcastReceivers are invoked based on events called Intents
"An intent is an abstract description of an operation to be performed."
What user wants to accomplish
Hold two key types of information: metadata and data for the component that receives it, and information for the system to resolve and process
http://groups.google.com/group/android-developers
http://stackoverflow.com/questions/tagged/android
Tools
More Demos
Getting stuff done
ListViews and Adapters
Alerts/Dialogs/Notifications
Location
Sensors
Networking
Databases
XML/JSON
Testing
http://code.google.com/p/and-examples/
RestaurantFinder
Multiple activities
Built in Intents used
Permissions in manifest
HTTP networking
XML SAX parsing
Location
LocationManager
Providers
Listeners
Sensors
Database
Internal app db (not a ContentProvider)
SQLiteDatabase
SQLiteOpenHelper
foreign keys
constraints
Basic SQL usage
Backup and restore database to SD card
Dynamic discovery
Retrieving values
Testing
Different test types
Multiple projects
Instrumentation
BookWorm
More advanced database
CursorAdapter
ListView with filter
PreferenceActivity
SurfaceView (capture camera images)
HttpHelper (Apache HttpClient)
SAX XML
Google ClientLogin Token
Thanks!
Other Resources
Droid-Fu
http://github.com/kaeppler/droid-fu
CommonsWare
http://commonsware.com/
Bunch of utils for the tricky stuff, nice
Great books
Very helpful guy - Mark Murphy
Manning Books
Good reviews
Getting updates
New titles
Maven-Android-Plugin
Droid-Draw
http://www.droiddraw.org/
UI Designer/Editor
Google IO Videos!
Horse's mouth
Third party "markets"
http://slideme.org/
http://andappstore.com
Context
Resources
SDK
Tools (android, adb, ddms, dx, many more)
Eclipse ADT
AVD Manager and components
APIs and framework
Agenda
Introduction
Platform overview
Market conditions
To the code! Hello World
Beyond Hello World
Key framework components
Tools
Testing?
Practical tips
More demos (time permitting)
Resources
Alerts/Dialogs/Notifications
AlertDialog
ProgressDialog (and progress bar)
NotificationManager/Notification
DevNexus
TableLayout
Simple ListView
Menu
Intents
Service
Background tasks
Started -- Context.startService() for long running
Bound -- connected and used by clients (Activities or other Services) as needed
Lifecycle
Permissions
AlarmManager to "wake" (rather than leave running)
Advanced topic
Maintaining State
Internal state -- Preferences (file system, via SharedPreferences)
External state -- data, SQLite, web services, and the like
Transient state -- in memory values in fields, choices, and so on
Make sure to save and maintain internal and external in onPause() (at least)
Configuration (orientation) change restarts and Activity (by default)
Use onSaveInstanceState and onRestoreInstanceState for transient state
onRetainNonConfigurationInstance -- special "optimization"
(can store anything with it, even entire Activity, but not guaranteed to run)
Ignore "onFreeze" (old diagram)
Specialized Activities
ListActivity
TabActivity
PreferenceActivity
Less boilerplate as many details
for the "task" at hand already covered.
Permissions
Activities can "enforce" (declare they require) permissions
Can define your own permissions
Consumers must declare "uses-permission" in manifest
CALL_PHONE, INTERNET, REBOOT -- etc
Different applications and actitivies
combine seamlessly to user.
Recent "tasks" switcher
All together now == Task
Root Activity
Hook to the application environment
Obtain "System" services
Inquire about status of available resources
(packages, hardware, intents)
Get handle to resources (file system, external storage, etc)
Check and enforce permissions
Application level operations
launch activities
Broadcasting intents
Receiving intents
Starting and binding services
More
A lot of stuff here . . .
but provided by the system,
easy to use and get to know.
startActivity(intent);
Intent intent = new Intent(Intent.VIEW_ACTION,
Uri.parse("http://www.google.com"));
startActivity(intent);
IntentFilter
Android's "Event Bus"
Action: what to do
Data: URI of data and MIME type
Category: Info about "kind of component" that should handle
Extras: key-value payload
Flags: System meta data (how to launch, task affinity)
Intent Data
Intent Resolution
Explicit
Implicit
Intent intent = new Intent(context, NextActivity.class);
Explicit (component present) -- done.
Implicit system must "resolve" intent with IntentFilter.
Manifests define filters
System maintains registry (ok, poor word, list?)
System resolves best match
See docs for resolution process detail
Special class that can catch broadcast events
Normally defined with <receiver> tag in manifest
Context.sendBroadcast(Intent, String)
BroadcastReceiver.onReceive(Context, Intent)
Permission aware
Example: BOOT_COMPLETED
<receiver android:name=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
public class BootCompletedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MyService.class));
}
}
Activity
Views and Layout
Resources
Task
Context
Share data across applications and processes.
Several built in providers (Contacts and Media)
REST "like"
Expose data in a table structure (with Cursor)
Do *not* have to be DB backed
More advanced topic
ContentProvider
Service
Component Processes and Threads
Activity, Service, ContentProvider, and BroadcastReceiver
all run in the same process for the app (by default)
All components run on the main Thread of said process
Be careful with all components, control process and userid
if needed, but better yet manage threads
Intents and IntentFilters
Custom Views
Your own widgets
On the fly Views
Composites
Non code stuff
Layout
Values
Drawables
XML
Animations
Raw
Resource Notes
Externalized from code, and
made nice for the people (efficiency, size).
XML compiled into binary fast loading form.
Strings compressed.
Remember R.java
also "android.R.*"
@+id/foo is the namespace of current application
@android:id/foo is the android namespace
gravity vs layout_gravity
Can be tricky
android:gravity positions the contents of that view (i.e. what’s inside the view)
android:layout_gravity positions the view with respect to its parent
adb shell
adb monkey
ddms
hierarchyviewer
adb logcat
android
does much more see -h
This *is* your dads computer (well, not that bad, but still)
Thanks to:
you
DevNexus Sponsors
AJUG (Burr, Gunnar, Sudhir)
Google and OHA
traceview
http://www.sonatype.com/books/mvnref-book/reference/android-dev.html
Testing
Automated testing can be done!
ant
android tool
instrumentation
unit vs functional
Android automated testing --
you've heard the stories, but
never actually seen it
Holy Grail
separate projects
separate test types
execute in IDE
automate on command line
code coverage and reports
test diff screen sizes and devices?
Beyond Hello World
Use the Google!
To the demos . . .
ps
meminfo
ls
layoutoptMore presentations by Charlie Collins
Java, only better: Google Guava
Charlie Collins on
An introduction to the Google Guava and Guice libraries.
Joda Time Overview
Charlie Collins on
A small simple presentation providing an overview of the main features of the Joda Time API.
Google I/O 2010 Recap
Charlie Collins on
A quick (and high level, not comprehensive) rundown of the action at Google I/O 2010
Popular presentations
30 Things About Me
Brooke Ahrens on
All About Brooke Ahrens- I used this presentation as an icebreaker to introduce myself to my classes this year.
More popular prezis in Explore>