2. What is the plan?
Java +Android Android UI Android in Action
(basics)
Layouts, ListView, Screen rotation,
JVM, GC, Threads, Memory analyze,
SDK, NDK, Activity, Menu, Dialog, Widgets,
Tips & tricks, etc. AIDL, SAX, Debug,
Code style, etc. Wakelock, etc.
Part I Part II Part III
3. Part I: Introduction
What is this about?
• Introduction to Java world
• JVM, Dalvik VM, JIT
• GC, multithreading, collections, etc.
• Android Basics
• Architecture
• Building blocks, SDK, NDK, etc.
• NDK demo
7. JVM
Class loader
class files
subsystem
The pc register (program counter)
Thread
JVM Stack
Native methods stacks
Heap
VM
Method Area
Сlass Runtime Constant Pool
native
Execution Native method method
engine interface libraries
8. Dalvik VM
• Was written by Dan Bornstein
• Transform class files into DEX
• It is VM…
– integrated with Linux
– uses shared memory, mmap
– for OS without swap space
– while powered by a battery
– zygote
• The Dalvik VM is register-based: fewer
instructions, code units, instructions
• Verification & optimization at Give me your huddled bytecodes
installation time yearning to run free. And I lift
the light beside the coder’s door
9. DEX file – shared constant pool
.jar file
.class file
heterogeneous .dex file
constant pool
string_ids “Hello World”
constant pool “Lcom/data/Data”
other data
type_ids int
constant pool String[ ]
.class file
proto_ids String fn()
heterogeneous constant pool void fn(int)
constant pool
field_ids String.offset
constant pool Integer.MAX_VALUE
other data
method_ids PrintStream.println(…)
constant pool Collection.size()
.class file
heterogeneous other data
constant pool
other data
10. DEX file – memory saving
• minimal repetition
• per-type pools (implicit typing)
• implicit labeling
common system libraries
(U) 21445320 — 100% (uncompressed jar file)
(J) 10662048 — 50% (compressed jar file)
(D) 10311972 — 48% (uncompressed dex file)
web browser app
(U) 470312 — 100%
(J) 232065 — 49%
(D) 209248 — 44%
• Google claims that Dalvik bytecode is more efficient than Sun’s stack
bytecode
11. JIT (since Android 2.2)
• Translates byte code to optimized native code at run time
• Part of the open source
• Trace JIT vs Method JIT
• Trace JIT
– Minimizing memory usage critical for mobile devices (100K)
– Important to deliver performance boost quickly
– Trace request is built during interpretation
– Compiled traces chained together in translation cache
– Per process translation cache
• Leave open the possibility of supplementing with method-
based JIT
13. Garbage collection
• GC is under control of the JVM
• An object is eligible for garbage i2
The heap
collection when no live thread can
access it i3 i2.n
• System.gc(); i4
Runtime.getRuntime().gc()
• static – variables with the longest
life time i3.n
i4.n
public class Island {
Island i;
public static void main(String[] args) {
Island i2 = new Island();
Island i3 = new Island();
Island i4 = new Island(); “Islands of Isolation”
i2.n = i3; i3.n = i4; i4.n = i2; x
i2 = null; i3 = null; i4 = null;
Island x = new Island(); x = null;
}
}
14. Mark and Sweep example
• Obtain locks and suspend threads Parallel mark bits in
Dalvik VM (separate from
• Mark phase other heap memory)
– Process of identifying all objects reachable from the root set.
– All “live” objects are marked by setting a mark bit in the mark bit vector.
• Sweep phase
– Sweep phase identifies all the
objects that have been allocated,
but no longer referenced.
• Compaction (optional)
– Once garbage has been removed,
we consider compacting the
resulting set of objects to remove
spaces between them.
• Release locks and resume threads
15. Generational GC
• Most recently created objects – most likely to become
unreachable quickly
Young Generation Old Generation
• Minor Collection – takes place only in the young generation,
normally done through direct copying – very efficient
• Major Collection – takes place in the new and old generation
and uses the normal mark/sweep (+compact) algorithm
16. Strings
• Strings are immutable in Java String x = “Hi";
String s1 = "abc"; // 1 object, 1 reference
String s2 = "abc"; The heap
// s1 == s2
String s3 = new String("abc"); // 2 “Hi”
objects, 1 reference x
String s4 = new String("abc");
// s3 != s4
// optimization by interning strings
x = x.concat(" GTUG!");
s3 = s3.intern();
s4 = s4.intern();
The heap
• Use StringBuffer, StringBuilder
“Hi”
• Set initial capacity of StringBuilder x
“Hi GTUG”
17. Quiz
class Foo {
int[] mArray = {
1, 2, 3, 4, 5
};
}
[ ref0, ref1, ref2]
public class Test {
public static void main(String[] args) {
Foo[] fa = new Foo[3]; Foo() []
fa[0] = new Foo();
Foo f = new Foo(); Foo() []
fa[1] = f;
f = null;
fa[1] = null;
// how many objects were created at this point?
// how many are eligible for gc()?
}
}
18. Performance
• Do not allocate memory as much as you can
• GC is slow (~x00 ms on Android device)
• Decrease number of objects – GC will work faster (i.e.
StringBuffer vs String)
• Use primitive types for arrays (int vs Integer)
• Use special methods: String.indexOf(), substring(), etc.
• Use exact class types instead of interfaces (i.e. HashMap
instead of Map) on devices without JIT
• Use static where possible ArrayList<MyClass> mList = new
• Avoid internal getters/setters ArrayList<MyClass>();
...
• Use enhanced for-loop syntax for (MyClass next : mList) {
...
}
20. References
• Strong reference: Object obj = new Object();
• SoftReference – soft references will be cleared before the JVM
reports an out-of-memory condition (memory-sensitive cache)
• WeakReference – gc frees weakly reachable object when it
founds it, avoid memory leaks (e.g.
http://en.wikipedia.org/wiki/Flyweight_pattern)
• PhantomReference – is useful only to track the impending
collection of the referring object. Must be used only with the
ReferenceQueue class. Most often used for scheduling pre-
mortem cleanup actions in a more flexible way than is possible
with the Java finalization mechanism
21. SoftReference: simple cache
private final HashMap<String, SoftReference<T>> mCache;
public put(String key, T value) {
mCache.put(key, new SoftReference<T>(value));
}
public T get(String key, ValueBuilder builder) {
T value = null;
SoftReference<T> reference = mCache.get(key);
if (reference != null) {
value = reference.get();
}
// Not in cache or gc'd
if (value == null) {
value = builder.build(key);
mCache.put(key, new SoftReference<T>(value));
}
return value;
}
22. git://android.git.kernel.org/platform/packages/apps/Mms.git/src/com/android/mms/model/ImageModel.java
package com.android.mms.model;
public class ImageModel extends RegionMediaModel {
private static final String TAG = "Mms/image";
private static final int THUMBNAIL_BOUNDS_LIMIT = 480;
private SoftReference<Bitmap> mBitmapCache = new SoftReference<Bitmap>(null);
...
private Bitmap internalGetBitmap(Uri uri) {
Bitmap bm = mBitmapCache.get();
if (bm == null) {
try {
bm = createThumbnailBitmap(THUMBNAIL_BOUNDS_LIMIT, uri);
if (bm != null) {
mBitmapCache = new SoftReference<Bitmap>(bm);
}
} catch (OutOfMemoryError ex) {
// fall through and return a null bitmap.
// The callers can handle a null
// result and show R.drawable.ic_missing_thumbnail_picture
}
}
return bm;
}
SoftReference
}
23. git://android.git.kernel.org/platform/frameworks/base.git/core/java/android/app/Dialog.java
package android.app;
public class Dialog implements DialogInterface, Window.Callback,
KeyEvent.Callback, OnCreateContextMenuListener {
...
private static final class ListenersHandler extends Handler {
private WeakReference<DialogInterface> mDialog;
public ListenersHandler(Dialog dialog) {
mDialog = new WeakReference<DialogInterface>(dialog);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DISMISS:
((OnDismissListener) msg.obj).onDismiss(mDialog.get());
break;
case CANCEL:
((OnCancelListener) msg.obj).onCancel(mDialog.get());
break;
case SHOW:
((OnShowListener) msg.obj).onShow(mDialog.get());
break;
}
}
} WeakReference
}
24. finalize()
• The finalize() method is guaranteed to run once and only once
before GC deletes an object
• GC makes no guarantees, finalize() may never run
• You can uneligibilize an object for GC within finalize()
• Do not use it for resource closing
31. Threads
• When it comes to threads, very little is guaranteed
• Create thread: extend java.lang.Thread or implement Runnable
interface
• A thread is done being a thread when its target run() method
completes
• Once a thread has been started, it can never be started again
• The order in which runnable threads are chosen is not
guaranteed
• sleep(long ms), yield(), join(), setPriority(int priority), wait(),
notify(), notifyAll()
32. Thread states
Waiting/
blocking
wait, sleep, join, lock
yield
New Runnable Running Dead
start() run() completes
not alive alive not alive
34. Synchronization
• Every Object in java has build-in lock
• Only methods or blocks can be synchronized
public static synchronized int getCount() {
return count;
}
public static int getCount() {
synchronized(MyClass.class) { // Class c = Class.forName(“MyClass”);
return count;
}
}
• notify(), join(), sleep(), yield() keep locks, wait() gives up lock
• synchronized keyword is not automatically inherited when
subclasses override superclass method
35. Volatile
public class Task extends Thread { class VolatileExample {
private volatile boolean mIsStop; int x = 0;
volatile boolean v = false;
public void run() {
public void writer() {
while (!mIsStop) { x = 42;
// do some stuff... v = true;
} }
}
public void reader() {
if (v == true) {
public void stopMe() {
// uses x - guaranteed to see 42.
mIsStop = true; }
} }
} }
volatile:
• Every thread accessing the field will read its current value before continuing, instead of
(potentially) using a cached value
• Statements accessing the variable will be executed in the order they are written (Java 5 or
later)
36. Singleton pattern example (1)
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
thread-safe
}
public class Singleton {
private static Singleton sInstance;
private Singleton() {}
public static Singleton getInstance() {
if (sInstance == null) {
sInstance = new Singleton();
}
return sInstance;
lazy init
}
} non-thread-safe
37. Singleton pattern example (2)
public class Singleton {
private static Singleton sInstance;
private Singleton() {}
public synchronized static Singleton getInstance() {
if (sInstance == null) {
sInstance = new Singleton();
} lazy init
return sInstance;
thread-safe
}
} low performance
38. Singleton pattern example (3)
public class Singleton {
private static Singleton sInstance;
private Singleton() {}
public static Singleton getInstance() {
if (sInstance == null) {
synchronized (Singleton.class) {
if (sInstance == null) { // “Double-Checked Locking” idiom
sInstance = new Singleton();
}
}
}
return sInstance;
}
}
39. Singleton pattern example (4)
public class Singleton {
private volatile static Singleton sInstance;
private Singleton() {}
public static Singleton getInstance() {
if (sInstance == null) {
synchronized (Singleton.class) {
if (sInstance == null) {
sInstance = new Singleton();
}
}
}
return sInstance;
}
} lazy init & thread-safe (Java 5 or later)
40. Singleton pattern example (5)
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
lazy init & thread-safe (for all Java version)
41. Quiz
public class Foo {
private static final int DELTA = 6;
private static Foo sInstance = new Foo();
private static int sBase = 7;
private int mX;
private Foo() {
mX = sBase + DELTA;
}
public static void main(String[] args) {
System.out.println(Foo.sInstance.mX);
}
}
What is the print? 6
44. Hash table
• Choosing a good hash function
• Collision resolution: separate chaining, open addressing
• Load factor
Key Hashcode Algorithm Hashcode 19 Bob 19 Bob
Alex A(1)+L(12)+E(5)+X(24) 42
33 Fred 33 Fred
Bob B(2)+O(15)+B(2) 19
42 Alex Dirk 42 Alex
Dirk D(4)+I(9)+R(18)+K(11) 42
43 Dirk
Fred F(6)+R(18)+E(5)+D(4) 33
• Find the right bucket (using hashCode())
• Search the bucket for the right element (using equals())
45. Contracts
The equals() contract
• Reflexive – x.equals(x)=true
• Symmetric – x.equals(y)=true -> y.equals(x)=true
• Transitive – x.equals(y)=true, y.equals(z)=true ->
x.equals(z)=true
• Consistent – multiple invocations
• x.equals(null)=false
The hashCode() contract
@Override
• Consistent during the app execution public int hashCode() {
return 1;
• If x.equals(y) -> hash must be the same }
47. Wrapper Classes and Boxing (1)
• The wrapper classes correlate to primitive types
• Wrappers have two main functions:
– To wrap primitives so that they can be handled like objects
– To provide utility methods for primitives (conversions)
• Wrapper constructors can take String (except Character)
• As of Java 5, boxing allows to convert primitives to wrappers or
vice versa automatically.
Integer x = 100;
x++;
int x2 = x.intValue();
x2++;
x = new Integer(x2);
48. Wrapper Classes and Boxing (2)
Integer i1 = 1000;
Integer i2 = 1000;
if (i1 != i2) System.out.println("i1!=i2"); i1!=i2
if (i1 == i2) System.out.println("i1==i2");
Integer i1 = 100;
Integer i2 = 100;
if (i1 != i2) System.out.println("i1!=i2"); I1==i2
if (i1 == i2) System.out.println("i1==i2");
JVM saves memory for:
• Boolean
• Byte
• Character from u0000 to u007f
• Short and Integer from -128 to 127
50. Java Code Style: why?
• 80% of the lifetime cost of a piece of software goes to maintenance
• Hardly any software is maintained for its whole life by the original
author
• Code conventions improve the readability of the software, allowing
engineers to understand new code more quickly and thoroughly
• Makes it easier to conduct code reviews
http://developers.sun.com/sunstudio/products/archive/whitepapers/java-style.pdf
51. Comments, TODOs, etc.
• Comments
• TODO, FIXME, XXX
– Use TODO comments for code that is temporary, a short-
term solution, or good-enough but not perfect.
• Copyrights
52. Android Code Style (1)
• Import ordering
– Android imports
– Imports from third parties (com, junit, net, org)
– java and javax
• Indentation
– We use 4 space indents for blocks. We never use tabs. When in doubt,
be consistent with code around you
– We use 8 space indents for line wraps, including function calls and
assignments
• Field Names
– Non-public, non-static field names start with m.
– Static field names start with s.
– Other fields start with a lower case letter.
– Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.
53. Android Code Style (2)
• Braces
– Braces do not go on their own line; they go on the same line as the code
before them
if (condition) {
body; // ok
}
if (condition) body; // ok - 1 line
if (condition)
body; // bad
• Line length
– Each line of text in your code should be at most 100 characters long.
• Annotations, Logging
http://source.android.com/submit-patches/code-style-guide
54. BAD Code Style sample (1)
for(int i=0;i<amount;++i)
db.execSQL(sqls[i]);
public static final int sMaxSQLsInTransaction= 1000;
if (delayed == true) {
...
} else {
...
}
Good:
XmlHttpRequest getCustomerId
class Html
long id
Bad:
XMLHTTPRequest getCustomerID
class HTML
long ID
55. BAD Code Style sample (2)
public static final boolean PushValues(String pattern,
ArrayList<Integer> patternIds,/*OUT */ArrayList<String> values)
{
int idsAmount= (null != patternIds ? patternIds.size() : 0);
if(0<idsAmount){
final int patternLen=(null!=pattern ? pattern.length():0);
if(0<patternLen){
for(int i=0; i<idsAmount; ++i){
if(!pushValues(pattern,patternLen,patternIds.get(i),values)){
return (false);
}
}
return (true);
}
}
return (false);
}
56. BAD Code Style sample (2)
public static final ArrayList<String> getValues(final String pattern,
final ArrayList<Integer> patternIds) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (pattern != null && pattern.length() > 0 && patternIds != null) {
for (int patternId : patternIds) {
ArrayList<Integer> values = getValuesForPatternId(pattern, patternId);
if (values == null) {
return null;
}
result.addAll(values);
}
}
return result;
}
58. Android basics
• Architecture Overview
• Building Blocks
• Manifest
• System Services
• Platform versions
• Saving Application State
• NDK
• Make your code better
59. Android
• Architecture Overview
• Building Blocks
• Manifest
• System Services
• Platform versions
• Saving Application State
• NDK
• Make your code better
60. Android History
• Jul 2005 – Google acquired Android Inc. (co-founded by Andy
Rubin)
• Nov 2007 – Google Android presentation and “early look”
release
Sep
2008 Éclair
Mar May Sep Oct Dec
1.0 2009 2009 2009 2009 2009 Froyo
Jan May
1.1 1.5 1.6 2.0 2.0.1 2010 2010
2.1 2.2
Cupcake
Donut Gingerbread
61. Android Architecture Overview
Applications
Home Contacts Phone Browser …
Application Framework
NDK / JNI
Activity Manager Window Manager Content Providers View System Resource Manager
Package Manager Telephony Manager Notification Manager Location Manager
Libraries Android Runtime
Surface Manager Media Framework SQLite Core Libraries
OpenGL | ES FreeType WebKit Dalvik VM
SGL SSL libc
Linux Kernel
Display Driver Camera Driver Flash Memory Driver Binder (IPC) Driver
Keypad Driver WiFi Driver Audio Drivers Power Management
62. Android
• Architecture Overview
• Building Blocks
• Manifest
• System Services
• Platform versions
• Saving Application State
• NDK
• Make your code better
63. Android Application Building Blocks
• Activity
– Presents UI
– Each Activity is independent screen
– Activity: setContentView(View)
• Service
– Used for background operations
• BroadcastReceiver
– Receive and process broadcast system or user events
• ContentProvider
– Share application data with others
– Data can be stored in FS, DB or even in memory
– Communicate via ContentResolver
• Intent
– Used to activate Activities, Services & BroadcastReceivers
http://developer.android.com/guide/topics/fundamentals.html
64. Android Application
• Controls global Application state
• Extend Application class (android.app.Application)
– onCreate()
– onLowMemory()
– onTerminate()
– getApplicationContext() – to use it in classes, where is no
Context
• Point custom Application class in AndroidManifest.xml
65. Android Context
Application Context Activity Context
• Non UI Context • Same as for Application, but specific
• startActivity(Intent) to current Activity
• start /stopService(Intent) • startActivityForResult(Intent) /
• sendBroadcast(Intent) finish()
• register / unregisterReciever() • bindService(Intent)
• Application FS, Preferences, • UI: setContentView(View),
Resources findViewById()
• getSystemService • User events handling (Keys,
Touches, Trackball)
66. Android
• Architecture Overview
• Building Blocks
• Manifest
• System Services
• Platform versions
• Saving Application State
• NDK
• Make your code better
71. Android
• Architecture Overview
• Building Blocks
• Manifest
• System Services
• Platform versions
• Saving Application State
• NDK
• Make your code better
72. Android System Services
Object getApplicationContext().getSystemService(String serviceName)
serviceName value Service Class name Description
(contsants in Context)
WINDOW_SERVICE WindowManager Controls on-screen windows
and their parameters
LAYOUT_INFLATER_SERVICE LayoutInflater Inflates layout resources
POWER_SERVICE PowerManager Controls power management
NOTIFICATION_SERVICE NotificationManager Status bar notifications
CONNECTIVITY_SERVICE ConnectivityManager Handling network connections
WIFI_SERVICE WifiManager Handling Wi-Fi network status
TELEPHONY_SERVICE TelephonyManager Handling phone calls states
LOCATION_SERVICE LocationManager Controls location (GPS) updates
SENSOR_SERVICE SensorManager Controls sensor
… … …
73. Android
• Architecture Overview
• Building Blocks
• Manifest
• System Services
• Platform versions
• Saving Application State
• NDK
• Make your code better
74. Android Platform Versions
• May 2009 – platform ver. 1.5
• May 2010 – platform ver. 2.2
• Six platform releases in a year (platform ver.1.1 is
hard to find on real phones)
• Platforms are back-compatible
• It is good point to be compatible with dominated
platforms (1.5, 1.6, 2.0.1 and 2.1)
• To use advantages of the latest platform versions,
Java Reflection mechanism should be used
76. Android Platform Fragmentation in Russia
Android 2.2 ; 0,5% Android 2.0 ; 0,1%
Android 2.0.1 ; 0,6%
Android 1.6 ; 21,7%
Android 1.5 ; 43,6%
Android 2.1; 33,6%
• Data gathered by Flurry service in real application
• About 0.5% of 2.1 in Russia are custom ROMs
77. Java Reflection
• Originally used to inspect classes, interfaces, fields and
methods at runtime, without knowing the names of them at
compile time. It can be used for observing and/or modifying
program execution at runtime
• Classes: Class, Method, Field, Constructor, etc.
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
78. Java Reflection and Android
public class ClassHolder {
private static NewClass foo;
public static void tryNewClass() {
foo = new NewClass();
}
}
try {
ClassHolder.tryNewClass();
// NewClass available
} catch (VerifyError e) {}
try {
Method methodName = ClassName.class.getMethod(...);
methodName.invoke(Object obj, Object... args);
} catch (NoSuchMethodException e) {}
try {
Field fieldName = ClassName.class.getField(...);
fieldName.getType(Object obj);
} catch (NoSuchFieldException e) {}
79. Java Reflection and Android (Example)
private static Field densityDpiField;
private static Field densityDpiLowResValue;
private static boolean sIsLowRes = false;
private static boolean sIsNormalRes = true;
static {
try {
densityDpiField = DisplayMetrics.class.getField("densityDpi");
densityDpiLowResValue = DisplayMetrics.class.getField("DENSITY_LOW");
} catch (NoSuchFieldException nfe) {
// Old device - no density Field
}
}
81. Java Reflection and Android (Example) (Cont.)
public static int scaleToDensity(int dp_size) {
if (dp_size == 0 || sIsNormalRes) {
return dp_size;
}
return (int)(dp_size *
sContext.getResources().getDisplayMetrics().density + 0.5f);
}
82. Android
• Architecture Overview
• Building Blocks
• Manifest
• System Services
• Platform versions
• Saving Application State
• NDK
• Make your code better
83. Saving State of Android Application
• Shared Preferences are stored in the application private data space
and can be shared only inside this Application, but between launches
and versions
• Instance of SharedPreferences class should be obtained:
Activity.getPreferences()
PreferenceManager.getDefaultSharedPreferences(Context ctx)
Context.getSharedPreferences(String name, int mode)
• To read:
mPreferences.getType(String key, T defValue);
• To write:
SharedPreferences.Editor editor = mPreferences.edit();
editor.putType(String key, T value);
editor.commit();
• SharedPreferences.OnSharedPreferenceChangeListener
84. Backup Application Data (android.app.backup – 2.2)
• Perform backup arbitrary data to remote “cloud” storage
• Easily perform backup of SharedPreferences and files
• Restore the data saved to remote storage
• Controlled by Android Backup Manager
– Extend class BackupAgent and override onBackup() & onRestore()
OR
– Extend BackupAgentHelper to backup/restore SharedPreferences and
files from internal storage
– Add your agent to AndroidManifest.xml
<application android:backupAgent=".MyBackupAgent" >
• BackupManager.dataChanged()/requestRestore()
• New bmgr tool for testing
http://developer.android.com/guide/developing/tools/bmgr.html
• Full guide with examples:
http://developer.android.com/guide/topics/data/backup.html
85. Android
• Architecture Overview
• Building Blocks
• Manifest
• System Services
• Platform versions
• Saving Application State
• NDK
• Make your code better
86. Android NDK (Native Development Kit)
• Provides ability and tools to embed components that make use
of native code in Android applications
• Supports only restricted set of native libraries:
– libc (C library) headers
– libm (math library) headers
– JNI interface headers
– libz (Zlib compression) headers
– liblog (Android logging) header
– OpenGL ES 1.1 (since 1.6) and OpenGL ES 2.0 (3D graphics
libraries, since 2.0) headers
– libjnigraphics (Pixel buffer access) header (since 2.2)
– A Minimal set of headers for C++ support
• For Windows Cygwin 1.7 (or higher) is needed
88. Android
• Architecture Overview
• Building Blocks
• Manifest
• System Services
• Platform versions
• Saving Application State
• NDK
• Make your code better
89. Designing for Performance
Action Time
• Use final for constants Add a local variable 1
• Avoid enums Add a member variable 4
Call String.length() 5
• Avoid float Call empty static native method 5
• Use local variables for access to Call empty static method 12
Call empty virtual method 12.5
object fields inside loops (or more
Call empty interface method 15
than once) Call Iterator:next() on a HashMap 165
• Don’t use private scope with Inner Call put() on a HashMap 600
Classes Inflate 1 View from XML 22,000
Inflate 1 LinearLayout containing 25,000
1 TextView
Inflate 1 LinearLayout containing 135,000
6 TextView objects
Launch an empty activity 3000,000
90. Designing for Responsiveness
• Application Not Responding (ANR) dialog:
– No response to an input event (e.g. key press, screen
touch) within 5 seconds
– A BroadcastReceiver hasn't finished executing within 10
seconds
• Quick Activity life-cycle methods (onCreate,
onResume) and all other methods working on UI
thread
• Use new Thread for long-time operations (i.e.
network/database operations, expensive
computations, bitmap resizing, etc.)
• Use ProgressBar or ProgressDialog to show
“Loading…” or use splash screen when starting
application
• To avoid long-time operations in BroadcastReceiver
– start Service (not Activity!)
91. Designing for Seamlessness
• React correctly on system events (i.e. phone call)
• onSaveInstanceState/onResumeInstanceState
• onPause/onResume
• TelephonyManager, etc.
• Share data using ContentProvider
• Use NotificationManager and Notifications from background
processes (Service, BroadcastReceiver)
• Don’t overload a single Activity screen – use several Activities for
correct dealing with history and Android “backstack” model
• Use Threads for long-time operations to avoid ANR
• Remember about multiple screen resolutions and multiple Android
platform versions
• Assume the Network is slow (change speed in Eclipse DDMS for
Emulator)
• Don’t assume Touchscreen or Keyboard
• Remember about battery life