1.
Android
Coding Convention
1.1 Don’t
Ignore Exception
void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) { }
}
1.2 Don’t
Catch Generic Exception
try {
someComplicatedIOFunction(); // may throw IOException
someComplicatedParsingFunction(); // may throw ParsingException
someComplicatedSecurityFunction(); // may throw SecurityException
// phew, made it all the way
} catch (Exception e) { // I'll just catch all exceptions
handleError(); // with one generic handler!
}
1.3 Fully
Qualify Imports
When you want to use class Bar from package foo,there are
two possible ways to import it:
import foo.*;
Pros: Potentially
reduces the number of import statements.
import foo.Bar;
Pros: Makes it obvious
what classes are actually used. Makes code more readable for maintainers.
Decision: Use the
latter for importing all Android code. An explicit exception is made for java
standard libraries (java.util.*, java.io.*, etc.) and unit test code
(junit.framework.*)
1.4 Use
Javadoc Standard Comments
/** Returns the correctly rounded positive square root of a double value.
*/
static double sqrt(double a) {
...
}
or
/**
* Constructs a new String by converting the specified array of
*/
public String(byte[] bytes) {
}
1.5 Conventions
that Don’t Hurt [No harm in following them, but their value is questionable]Put
Open Braces with Preceding Code.
Yes
public void foo() {
if (...) {
doSomething();
}
}
No
public void foo()
{
if (...)
{
doSomething();
}
}
1.6 Use
Spaces For Indentation
We use 8 space indents for line wraps, including function
calls and assignments. For example,
this is correct:
Instrument i =
someLongExpression(that, wouldNotFit, on, one, line);
and this is not correct:
Instrument i =
someLongExpression(that, wouldNotFit, on, one, line);
1.7 Follow
Filed Naming Convention
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.
public class MyClass {
public static final int SOME_CONSTANT = 42;
public int publicField;
private static MyClass sSingleton;
int mPackagePrivate;
}//A class following Field Naming Conventions
1.8 Treat
Acronyms as Words
Treat acronyms and abbreviations
as words in naming variables, methods, and classes. The names are much more
readable:
Good Bad
XmlHttpRequest XMLHTTPRequest
getCustomerId getCustomerID
class Html class HTML
String url String URL
long id long ID
1.9 Use
TODO Comments
2.
The
Golden Rules of Performance
• Don't do work that you
don't need to do
• Don't allocate memory if you can avoid it
2.1 Performance
Pointers
2.1.1
Avoid creating objects
Object creation is
never free. A generational GC with per-thread allocation pools for temporary
objects can make allocation cheaper, but allocating memory is always more
expensive than not allocating memory.
If you allocate
objects in a user interface loop, you will force a periodic garbage collection,
creating little "hiccups" in the user experience. The concurrent
collector introduced in Gingerbread helps, but unnecessary work should always
be avoided.
Thus, you should
avoid creating object instances you don't need to. Some examples of things that
can help:
- If you have a method returning a
string, and you know that its result will always be appended to a
StringBuffer anyway, change your signature and implementation so that the
function does the append directly, instead of creating a short-lived
temporary object.
- When extracting strings from a set
of input data, try to return a substring of the original data, instead of
creating a copy. You will create a new String object, but it will share
the char[] with the data. (The trade-off being that if you're only using a
small part of the original input, you'll be keeping it all around in
memory anyway if you go this route.)
A somewhat more
radical idea is to slice up multidimensional arrays into parallel single
one-dimension arrays:
- An array of ints is a much better
than an array of Integers, but this also generalizes to the fact that two
parallel arrays of ints are also a lot more efficient than an array
of (int,int) objects. The same goes for any combination of primitive
types.
- If you need to implement a
container that stores tuples of (Foo,Bar) objects, try to remember that
two parallel Foo[] and Bar[] arrays are generally much better than a
single array of custom (Foo,Bar) objects. (The exception to this, of
course, is when you're designing an API for other code to access; in those
cases, it's usually better to trade good API design for a small hit in
speed. But in your own internal code, you should try and be as efficient
as possible.)
Generally speaking,
avoid creating short-term temporary objects if you can. Fewer objects created
mean less-frequent garbage collection, which has a direct impact on user
experience.
2.1.2
Prefer Static Over Virtual
If you don't need to access an object's fields, make
your method static. Invocations will be about 15%-20% faster. It's also good
practice, because you can tell from the method signature that calling the
method can't alter the object's state.
2.1.3
Avoid Internal Getters/ Setters
In native languages like C++ it's common practice to
use getters (e.g. i = getCount()) instead of accessing the field directly (i =
mCount). This is an excellent habit for C++, because the compiler can usually
inline the access, and if you need to restrict or debug field access you can
add the code at any time.
On Android, this is a bad idea. Virtual method calls
are expensive, much more so than instance field lookups. It's reasonable to
follow common object-oriented programming practices and have getters and
setters in the public interface, but within a class you should always access
fields directly.
2.1.4
Use Static Final For Constants
Consider the following declaration at the top of a
class:
static int intVal = 42;
static String strVal = "Hello, world!";
The compiler generates a class initializer method,
called <clinit>, that is executed when the class is first used. The
method stores the value 42 into intVal, and extracts a reference from the
classfile string constant table for strVal. When these values are referenced
later on, they are accessed with field lookups.
We can improve matters with the "final"
keyword:
static final int intVal = 42;
static final String strVal = "Hello, world!";
The class no longer requires a <clinit> method,
because the constants go into static field initializers in the dex file. Code
that refers to intVal will use the integer value 42 directly, and accesses to
strVal will use a relatively inexpensive "string constant"
instruction instead of a field lookup. (Note that this optimization only
applies to primitive types and String constants, not arbitrary reference types.
Still, it's good practice to declare constants static final whenever possible.)
2.1.5
Use Enhanced For Loop Syntax
The
enhanced for loop (also sometimes known as "for-each" loop) can be
used for collections that implement the Iterable interface and for arrays. With
collections, an iterator is allocated to make interface calls to hasNext() and
next(). With an ArrayList, a hand-written counted loop is about 3x faster (with
or without JIT), but for other collections the enhanced for loop syntax will be
exactly equivalent to explicit iterator usage.
There are
several alternatives for iterating through an array:
static class Foo {
int mSplat;
}
Foo[] mArray = ...
public void zero() {
int sum = 0;
for (int i = 0; i < mArray.length; ++i) {
sum += mArray[i].mSplat;
}
}
public void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; ++i) {
sum += localArray[i].mSplat;
}
}
public void two() {
int sum = 0;
for (Foo a : mArray) {
sum += a.mSplat;
}
}
zero() is slowest,
because the JIT can't yet optimize away the cost of getting the array length
once for every iteration through the loop.
one() is faster. It
pulls everything out into local variables, avoiding the lookups. Only the array
length offers a performance benefit.
two() is fastest for
devices without a JIT, and indistinguishable from one() for devices
with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of
the Java programming language.
To
summarize: use the enhanced for loop by default, but consider a hand-written
counted loop for performance-critical ArrayList iteration.
2.1.6
Consider Package Instead Of Private Access
With Private Inner Classes
Consider
the following class definition:
public class Foo {
private class Inner {
void stuff() {
Foo.this.doStuff(Foo.this.mValue);
}
}
private int mValue;
public void run() {
Inner in = new Inner();
mValue = 27;
in.stuff();
}
private void doStuff(int value) {
System.out.println("Value is " + value);
}
}
The key
things to note here are that we define a private inner class (Foo$Inner
) that directly
accesses a private method and a private instance field in the outer class. This
is legal, and the code prints "Value is 27" as expected.
The
problem is that the VM considers direct access to Foo
's private members
from Foo$Inner
to be illegal
because Foo
and Foo$Inner
are different
classes, even though the Java language allows an inner class to access an outer
class' private members. To bridge the gap, the compiler generates a couple of
synthetic methods:
/*package*/ static int Foo.access$100(Foo foo) {
return foo.mValue;
}
/*package*/ static void Foo.access$200(Foo foo, int value) {
foo.doStuff(value);
}
The inner
class code calls these static methods whenever it needs to access the mValue
field or invoke
the doStuff
method in the
outer class. What this means is that the code above really boils down to a case
where you're accessing member fields through accessor methods. Earlier we
talked about how accessors are slower than direct field accesses, so this is an
example of a certain language idiom resulting in an "invisible"
performance hit.
If you're
using code like this in a performance hotspot, you can avoid the overhead by
declaring fields and methods accessed by inner classes to have package access,
rather than private access. Unfortunately this means the fields can be accessed
directly by other classes in the same package, so you shouldn't use this in
public API.
2.1.7
Know And Use The Library
In addition to all the usual reasons
to prefer library code over rolling your own, bear in mind that the system is
at liberty to replace calls to library methods with hand-coded assembler, which
may be better than the best code the JIT can produce for the equivalent Java.
The typical example here is String.indexOf
and friends, which Dalvik replaces
with an inlined intrinsic. Similarly, the System.arraycopy
method is about 9x faster than a
hand-coded loop on a Nexus One with the JIT.
2.2
Responsiveness
Avoid modal Dialogues and Activities
• Always
update the user on progress (ProgressBar and
ProgressDialog)
• Render
the main view and fill in data as it arrives
"Application Not Responding"
• Respond
to user input within 5 seconds
• Broadcast
Receiver must complete in 10 seconds
Users perceive a lag longer than 100 to 200ms
Use Threads and AsyncTasks within Services
2.3 Gluttony
2.3.1
Don'ts
• DON'T over use WakeLocks
• DON'T update Widgets too
frequently
• DON'T update your location
unnecessarily
• DON'T use Services to try to
override users or the system
2.3.2
Dos
• DO share data to minimize duplication
• DO use Receivers and Alarms not Services and Threads
• DO let users manage updates
• DO minimize resource contention
2.3.3
What is a WakeLock?
·
Force the CPU to keep running
·
Force the screen to stay on (or stay bright)
·
Drains your battery quickly and
efficiently
PowerManager pm =
(PowerManager)getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl =
pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
"My Wakelock");
wl.acquire();
// Screen and power stays on
wl.release();
2.3.4
Using WakeLocks
• Do
you really need to use one?
• Use
the minimum level possible
o PARTIAL_WAKE_LOCK
o SCREEN_DIM_WAKE_LOCK
o SCREEN_BRIGHT_WAKE_LOCK
o FULL_WAKE_LOCK
•
Release as soon as you can
•
Specify a timeout
• Don't use them in Activities
2.3.5
Window Managed WakeLocks
·
No need for permissions
·
No accidently leaving the screen from the
background
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
2.4 Hostility
2.4.1
User experience should be your top priority
2.4.2
Respect user expectations for navigating your app
·
The back button should always
navigate back through previously seen screens
·
Always support trackball navigation
·
Understand your navigation flow when entry point
is anotification or widget
·
Navigating between application elements should be
easy and intuitive
2.4.3
Don't hijack the native experience
·
Don't hide the status bar
·
Back button should always navigate through
previous screens
·
Use native icons consistently
·
Don't override the menu button
·
Put menu options behind the menu button
2.4.4
Respect user preferences
• Use only enabled location-based services
• Ask permission before transmitting location
data
• Only transfer data in the background if user
enabled
ConnectivityManager cm =
(ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
boolean backgroundEnabled = cm.getBackgroundDataSetting();
2.5 Arrogance
• Don't use undocumented APIs
• Make your app behave consistently with the
system
• Respect the application lifecycle model
• Support both landscape and portrait modes
• Don't disable rotation handling
2.6 Size
Discrimination
·
Don't make assumptions about screen size or
resolution
·
Use Relative Layouts and device independent
pixels
·
Optimize assets for different screen resolutions
2.7 Ensuring
Future Hardware Happiness
·
Specify uses-feature node for every
API you use.
·
Mark essential features as required.
·
Mark optional features as not
required.
<uses-feature
android:name="android.hardware.location"
android:required="true"/>
<uses-feature
android:name="android.hardware.location.network"
android:required="false"/>
<uses-feature
android:name="android.hardware.location.gps"
android:required="false"/>
·
Check for API existence in code.
PackageManager pm = getPackageManager();
boolean hasCompass =
pm.hasSystemFeature(
PackageManager.FEATURE_SENSOR_COMPASS);
if (hasCompass) {
// Enable things that require the compass.
}
3.
The
Five Glorious Virtues
3.1 Beauty
• Create assets optimized for all screen
resolutions
o Start with vectors or high-res raster art
o Scale down and optimize for supported screen
• Support resolution independence
• Use tools to optimize your implementation
o layoutopt
o hierarchyviewer
3.2 Generosity
3.2.1
Use Intents to leverage other people's apps
• Works just like your own Activity
• Can pass data back and forth between
applications
•
Return to your Activity when closed
String
action = "com.hotelapp.ACTION_BOOK";
String
hotel = "hotel://name/" + selectedhotelName;
Uri
data = Uri.parse(hotel);
Intent
bookingIntent = new Intent(action, data);
startActivityForResult(bookingIntent);
3.2.2
Define Intent Filters to share your functionality
• Indicate the ability to perform an action on
data
• Specify an action you can perform
• Specify the data you can perform it on
<activity
android:name="Booking" android:label="Book">
<intent-filter>
<action
android:name="com.hotelapp.ACTION_BOOK" />
<data
android:scheme="hotel"
android:host="name"/>
</intent-filter>
</activity>
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(r.layout.main);
Intent intent = getIntent();
String action = intent.getAction();
Uri data = intent.getData();
String hotelName = data.getPath();
// TODO Provide booking functionality
setResult(RESULT_OK, null);
finish();
}
3.3 Ubiquity
• Create widgets
• Surface search results into the Quick Search
Box
• Live Folders
• Live Wallpapers
• Expose Intent Receivers to share your
functionality
• Fire notifications
3.4
Utility & Entertainment
• Create an app that solves a problem
• Present information in the most useful way
possible
• Create games that are ground breaking and
compelling
4.
What we
should do and don’t
4.1 Let the
runtime kill your background Service
4.1.1
For Services that perform a single action / polling
4.1.2
Reduces resource contention
@Override
public int onStartCommand(Intent
intent, int f, int sId) {
handleCommand(intent);
return START_NOT_STICKY;
}
@Override
public void onStart(Intent intent,
int sId) {
handleCommand(intent);
}
4.1.3
Kill your own Service
@Override
public
int onStartCommand(Intent i, int f, int sId) {
myTask.execute();
return
Service.START_NOT_STICKY;
}
AsyncTask<Void,
Void, Void> myTask =
new
AsyncTask<Void, Void, Void>() {
@Override
protected
Void doInBackground(Void... arg0) {
// TODO
Execute Task
return
null;
}
@Override
protected
void onPostExecute(Void result) {
stopSelf();
}
};
4.2
Use Alarms and Intent Receivers
• Schedule updates and polling
• Listen for system or application events
• No
Service. No Activity. No running Application.
4.2.1
Intent Receivers
<receiver
android:name="MyReceiver">
<intent-filter>
<action
android:name="REFRESH_THIS" />
</intent-filter>
</receiver>
public
class MyReceiver extends BroadcastReceiver
{
@Override
public
void onReceive(Context context, Intent i) {
Intent
ss = new Intent(context, MyService.class);
context.startService(ss);
}
}
4.2.2
Alarms
4.2.3
Use inexact Alarms
• All the Alarm goodness
• Now with less battery drain!
int type = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
long triggerTime = SystemClock.elapsedRealtime() +
interval;
am.setInexactRepeating(type, triggerTime,interval, op);
4.3
Location Based Services
String serviceName = Context.LOCATION_SERVICE;
lm = LocationManager)getSystemService(serviceName);
LocationListener l = new LocationListener() {
public void onLocationChanged(Location location) {
// TODO Do stuff when location changes!
}
public void onProviderDisabled(String p) {}
public void onProviderEnabled(String p) {}
public void onStatusChanged(String p, int s, Bundle e) {}
};
lm.requestLocationUpdates("gps", 0, 0, l);
• How often do you need updates?
• What happens if GPS or Wifi LBS is disabled?
• How accurate do you need to be?
• What is the impact on your battery life?
• What happens if location 'jumps'?
4.3.1
Restricting Updates
• Specify the minimum update frequency
• Specify the minimum update distance
int
freq = 5 * 60000; // 5mins
int
dist = 1000; // 1000m
lm.requestLocationUpdates("gps",
freq, dist, l);
4.3.2
Use Criteria to Select a Location Provider
Criteria
criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(false);
String
provider = lm.getBestProvider(criteria, true);
lm.requestLocationUpdates(provider,
freq, dist, l);
• Specify your requirements and preferences
o Allowable power drain
o Required accuracy
o Need for altitude, bearing, and speed
o Can a cost be incurred?
• Find the best provider that meets your criteria
• Relax criteria (in order) until a provider is
found
• Can limit to only active providers
• Can use to find all matching providers
4.3.3
Implement a Back-off Pattern
• Use multiple Location Listeners
o Fine and coarse
o High and low frequency / distance
• Remove listeners as accuracy improves
Location Based Services
lm.requestLocationUpdates(coarseProvider,0,0,
lcourse);
lm.requestLocationUpdates(fineProvider,
0, 0, lbounce);
private
LocationListener lbounce = new LocationListener(){
public
void onLocationChanged(Location location) {
runLocationUpdate();
if
(location.getAccuracy() < 10) {
lm.removeUpdates(lbounce);
lm.removeUpdates(lcoarse);
lm.requestLocationUpdates(provider,
freq, dist, l);
}
}
};
private
LocationListener lcoarse = new LocationListener(){
public
void onLocationChanged(Location location) {
runLocationUpdate();
lm.removeUpdates(lcoarse);
}
};
5. Static Analysis Tools
http://pmd.sourceforge.net/pmd-5.0.0/