You are on page 1of 54

A Developer's perspective on Google Android

Gavin Bong @ Barcamp Malaysia 2008


rubycoder@gmail.com
Attributions
● Ben Lorica, Oreilly – for permission to use the graphs on
slides 51-53 which are taken from his research.
● All graphics featuring little green androids are produced by

the google android team & used in accordance with the


CC attribution 3.0 license.
● Terrence Barr – for the title used in slide 47.

● OpenIntents – for being such a good resource to

beginners to Android.
● Google I/O 2008 – for some kickass presentations which

taught me some of the things discussed in this talk.


● Max Braun and Rafael Spring - The guys behind Enkin.

● Jeffrey Sharkey – author of Android-Scan

● Dave – who wrote An Ode to team Android (slide 48).

● Last but not least, a big thanks to Kamal for inviting me to

give this talk & for organizing Barcamp Malaysia.


SQLite WIFI
OpenGL ES
3G
WebKit
MP3, AAC, AAC+ Bluetooth

GTalk H.264
QVGA / HVGA
Telephony Accelerometer
Touchscreen
Compass
GPS
Flash, SVG
Agenda
● An android application deconstructed

● Under the hood

● API Building Blocks

● Is Android lost in space ?

● Would you bet your career on Android ?

● Endgame: ideas to inspire you (demos)


Demo
twam = twitter + maps
If I ever complete “twam”, it will be opensourced at
http:// raverun.com / projects / twam
*.apk innards

$ jar tvf twam.apk

983 res/drawable/bubble.png
6121 res/drawable/icon.png
608 res/drawable/shadow.png
4068
864
res/layout/login.xml
res/layout/main.xml Android ≠ Java
924 res/layout/map_of_user.xml
3468 AndroidManifest.xml
1676 resources.arsc
94811 classes.dex

$ head -n 4 AndroidManifest.xml

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


<manifest
xmlns:android=”http://schemas.android.com/apk/res/android"
package="com.raverun.twam">
deploying twam.apk

classes.dex

$ adb install twam.apk Dalvik VM


Scanning package: /data/app/twam.apk
Adding package com.raverun.twam
zip_openZipFile(/data/app/twam.apk)
Registered content provider: com.raverun.twam,
className=com.raverun.twam.provider.TwitterPostProvider,
isSyncable = false
Providers:com.raverun.twam.provider.TwitterPostProvider
Services: com.raverun.twam.service.AuthServiceImpl
Activities: com.raverun.twam.LoginActivity
com.raverun.twam.GeocodeActivity
com.raverun.twam.TweetsList
com.raverun.twam.MapLocationViewer
android filesystem
android filesystem

/ data / data / package.name / ...


APis used in twam

Maps Google Maps


JSON org.json.*
HTTP Apache HTTPClient
org.apache.http.client
org.apache.commons.httpclient (m3)

Networking options
java.net.*
java.nio.*
APis used in twam

XML SAX kXML2


android.content.Resources
getAnimation( int id ) : XmlPullParser
getXml( int id ) : XmlPullParser
getLayout( int id ) : XmlPullParser

Database SQLite
Persistence options
SharedPreferences
Filesystem
Other databases: db4o, berkeleydb, neo4j
● An android application deconstructed


Under the hood
● API Building Blocks

● Is Android lost in space ?

● Would you bet your career on Android ?

● Endgame: ideas to inspire you (demos)


Linux core

● 2.6.24 kernel ( git.android.org )


GPLv2 + mix of LGPL, Apache v2.
Why? OHA members donated IPs.
● No swap space
Base profile: 64MB (20MB libraries)
Low memory killer (LRU)
● No glibc support
bionic libc (BSD + space/time optimized)
Linux process sandboxing

● 1 userid per process.


1 process per package.
● Pay attention to component lifecycle.

● Transparent IPC apk


● Binder
● Ashmem Dalvik VM
● aidl

libc
Linux process sandboxing

● adb ps

# kill -9 <pid>
# kill -15 <pid>
Threads
● An android application deconstructed

● Under the hood


API Building Blocks
● Is Android lost in space ?

● Would you bet your career on Android ?

● Endgame: ideas to inspire you (demos)


API Building blocks

Activity ( View )

Services

ContentProvider

Intent ( IntentReceiver )
Activities & Views
● Activity = Screen, View = UI widget

$ adb install twam.apk


Scanning package: /data/app/twam.apk
Adding package com.raverun.twam
zip_openZipFile(/data/app/twam.apk)
Registered content provider: com.raverun.twam,
className=com.raverun.twam.provider.TwitterPostProvider,
isSyncable = false
Providers:com.raverun.twam.provider.TwitterPostProvider
Services: com.raverun.twam.service.AuthServiceImpl
Activities: com.raverun.twam.LoginActivity
com.raverun.twam.GeocodeActivity
com.raverun.twam.TweetsList
com.raverun.twam.MapLocationViewer
Activities & Views

● ViewGroups are composites of Views.


● Layouts are ViewGroups.

● Vast improvements over J2ME


● Activity Stack (Task)

● ScrollView

● Modern & richer API

● 2 ways to declare Views.


● Programmatic.

● Externalized in XML layout files. (inflater)


Choose XML

<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textSize=”18sp”
>

DisplayMetrics dm = ...
TextView text = ...

text.setTextSize(
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
18,
dm )
);
Lifecycle of Activities

● Complex (due to LMK)


● Android delegates the swap out/swap in

of data for your Activities to the developer.


● Investigate the order of calls on callbacks.

class Activity ..
# onCreate( Bundle )
# onDestroy()
# onFreeze( Bundle )
# onResume()
# onPause()
Normal lifecycle
Simulate low memory
Low memory lifecycle
Implementation of onFreeze

protected void onFreeze( Bundle outState )


{
EditText field = findViewById( this,
EditText.class, R.id.userid );
outState.putCharSequence( "userid",
field.getText() );
}

protected void onCreate( Bundle icicle )


{
// ....code snipped...
EditText field = findViewById( this,
EditText.class, R.id.userid );
if( icicle != null )
field.setText(icicle.getCharSequence(“userid”));
}
Demo
Custom View (Graph)
browser
Activities and threading

● Never run long running tasks in the


callbacks and input handlers of an
Activity. Why?
● #1 Use child threads.
● #2 Use a Handler.

● #3 Use a Service.

Handler handler =
new Handler();
handler.post( new Runnable() {
// update UI elements
} );
Intents

An intent is an operation.

VIEW_ACTION geo:latitude,longitude
EDIT_ACTION content://contacts/1

bindService( new Intent


( AuthService.class.getName() ),
mConnection, Context.BIND_AUTO_CREATE )
Intents

An intent can carry payload. (e.g. twam)


Bundle bundle = new Bundle();
bundle.putInt( "latitude",
wrapper.latitude.intValue() );
bundle.putInt( "longitude",
wrapper.longtitude.intValue() );
bundle.putString( "name", wrapper.name );

Intent intent = new Intent();


intent.setClass(this,MapLocationViewer.class);
intent.putExtras( bundle );

startSubActivity( intent, 0 );
Intents

Intents allow loose coupling.


<activity android:name=".GeocodeActivity">
<action android:name="android.intent.action.MAIN" />
<category android:name="com.raverun.HOMESCREEN" />
</activity>

Intent mainIntent = new


Intent( Intent.MAIN_ACTION, null );

mainIntent.addCategory( "com.raverun.HOMESCREEN" );

PackageManager pm = getPackageManager();
List<ResolveInfo> list =
pm.queryIntentActivities(mainIntent, 0);
Intents

Intents can be broadcasted; to be handled by


IntentReceivers.

Intent intent = new


Intent(Constants.NEO_SERVICE_STARTED_ACTION);

intent.putExtra( Constants.SERVICE_KEY, 9 );

broadcastIntent( intent ); // async


Quirky Android

Simple logging
Log.d ( String tag, String msg )

Log.e ( .. )

Log.i ( .. )

Log.v ( .. )

Log.w ( .. )
Services

● Shares functionality behind an interface.


● Ability to run in its own process.
Services

<service
android:name=”.service.AuthServiceImpl”
android:process=”:remote”>
<intent-filter>
<action
android:name=
”com.raverun.twam.remote.AuthService”/>
</intent-filter>
</service>
Services
Background processes
● No jailbreaking required !

<uses-permission
android:name=
“android.permission.RECEIVE_BOOT_COMPLETED”/>

<receiver
android:name=
“.twam.services.OnBootStartService”/>
<intent-filter>
<action android:name=
“android.intent.action.BOOT_COMPLETED” />
</intent-filter>
</receiver>
ContentProviders

class SQLiteDatabase ..
+ execSQL( String sql ) : void
+ rawSQL( String sql, .. ) : Cursor
● Use ContentProviders for shareable data.
● REST-based
class ContentProvider ..
+ query( Uri, ...) : Cursor
+ insert( Uri, ...) : Uri
+ update( Uri, ...) : int
+ delete( Uri, ...) : int
ContentProviders
● URI examples
content : // browser / bookmarks
content : // contacts / people / 23
content : // com.raverun.twam / posts / 860701076
content : // com.raverun.twam / users / 9742542
● Utilities to process & compare URIs
URL_MATCHER = new UriMatcher( UriMatcher.NO_MATCH );
URL_MATCHER.addURI( TwitterPost.AUTHORITY,"posts/#",
POST_ID );
switch( URL_MATCHER.match(uri) )
{
case POST_ID:
// handle it
ContentProviders
(twam) Query for a user

Uri uri = Uri.parse(


“content://com.raverun.twam/users/23” );
String[] PROJECTION = {
TwitterPost.UserColumns._ID,
TwitterPost.UserColumns.LATITUDE,
TwitterPost.UserColumns.LONGITUDE
};
Cursor cursor =
getContentResolver().query( uri,
PROJECTION, null, null, null );
ContentProviders - Lessons
● Forgetting to close/requery-after-update Cursors.
class Activity ..
+ managedQuery( Uri, .. ):Cursor
+ managedCommitUpdates( Cursor ):void
● Unable to get field slot exception.
Dereferencing a column which is not specified
in the PROJECTION array
● CursorIndexOutOfBoundsException exception.
Cursor.first();
Developer resources

● http://code.google.com/p/android-positron/
Apache 2.0
● http://code.google.com/p/openintents/
Apache 2.0

● http://androidguys.com/

● http:///www.anddev.org/
Books

● Busy coder's guide to Android 1.0


http://commonsware.com/

● Pragmatic Programmer's Hello Android


(beta)
http://blogs.zdnet.com/Burnette/?p=619
● An android application deconstructed

● Under the hood

● API Building Blocks


Is Android lost in space ?
● Would you bet your career on Android ?

● Endgame: ideas to inspire you (demos)


1
Android lost in space ?

● Physical handsets delayed till Q4, 2008.


● No new SDK updates
m3 dec 14, 2007
m5rc14 feb 13, 2008
m5rc15 mar 03, 2008

● GPL violation ? NDA

[ 1 ] Terrence Barr, 10 July 2008


Your schedules are tight,
the handsets can't wait.
You have to release,
in 4Q O-Eight.

We do wish you luck,


as you test through the nite.
and code through the day,
But...
Could you please please P.S.
give us a new SDK? We don't mind if its buggy,
and not tested so well.
The old SDK,
is giving us hell.
Google's official word ?
- Dave
Crippled XMPP ?

● (m3) IXmppService renamed to


(m5) IGTalkService.
● Limitations of IGTalkService:

● Only talks to Google's servers.

● Not real XMPP.

● Reasons:

● Performance overheads

● Battery life problems

Speculation: XMPP in post 1.0 release ?


● An android application deconstructed

● Under the hood

● API Building Blocks

● Is Android lost in space ?

● Would you bet your career on Android ?

● Endgame: ideas to inspire you (demos)


Mailing lists traffic
Jobs
Jobs: Android vs iPhone
Demo
Android-scan + Enkin
vlc