Best practices for mobile app development android march 15 2013 ts
1. Best Practices for Mobile
Application Development on Android
Tasneem Sayeed
March 15, 2013
people
2. Intuit at a Glance
A Leading Provider of Business and
Financial Management Solutions
• Founded in 1983
• FY 2012 revenue of $4.1 billion
• Traded on the Nasdaq: INTU
• Employs more than 8,000 people
• Offices across the U.S., Canada, India and U.K.
• 60 million people use our QuickBooks, Payroll,
Payments, TurboTax, financial institution solutions,
Mint and Quicken products and services
4. Intuit apps
ProFile Connect
TurboTax SnapTax TaxCaster EITC Finder
Accounting
Finance Finance Finance
iOS
Canada
TurboTax MyTaxRefund
For the iPad Finance
Intuit Tax Online
Finance
Accountant
Finance
Mint.com
Intuit Health
Finance
Debit Card
Finance
Online Banking for
Financial Institutions
Quicken
GoPatient Finance
Medical Practice
Intuit QuickBooks Online SnapPayroll MyBizTracker
GoPayment Mobile Payroll Business Business
Business Business Business iOS
UK
Weave Intuit
Intuit Small MoneyDue
Productivity PaperTrail
Business Blog Business
Business
Business
6. Agenda
• Golden Rules & Best Practices of Performance
– Keeping your apps responsive
• What triggers ANR and how to avoid ANR?
– Running Background Services
– Improving the Performance & Scalability of long-running
operations by dispatching work to multiple threads
• Best Practices for User Experience
– Designing effective navigation
• Designing for Multiple Screens
• Designing for Multiple Orientations
7. Agenda
•Best Practices for User Experience
– Implementing Effective Navigation
• How to correctly handle the Back button
•Benefits of Intents and Intent Filters
•Summary
8. Golden Rules & Best Practices for
Performance
• Two Basic Rules for Writing Efficient Code:
– Don’t do work that you don’t need to do
– Don’t allocate memory if you can avoid it
• Reduce Object Creation
– Allocating more objects than you need in your app will force
a periodic garbage collection
9. Best Practices for Performance
• Reducing Object Creation
– Examples:
• String is immutable, so if you alter their values then another object
gets created, whereas StringBuffer and StringBuilder are mutable so
they can change their values
- If you string is not going to change => use a string Class because a String
object is immutable
- If your string can change and only accessed from a single thread => using a
StringBuilder will suffice
- If your string can change and will be accessed from multiple threads, use a
StringBuffer as it is thread-safe
• Slice up multidimensional arrays into parallel single one-dimensional
arrays
- An array of ints is much better than an array of Integer objects
- Two parallel arrays of ints are more efficient than an array of (int,int) objects
• Prefer Static over Virtual
• If you don’t need to access an object’s fields, make your method static
- Invocations => 15%-20% faster
10. Best Practices for Performance
• Use Static Final for Constants
– Using the “final” keyword => 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 10 directly
– Accesses to strVal will use an inexpensive “string constant” instead
of field lookup
11. Best Practices for Performance
• Avoid Internal Getters and/or Setters
–In native languages like C++, it’s common practice to use getters
and setters (num = getCount()) instead of accessing the filed
directly (num = count). It’s a great habit for C++, and several
other object oriented languages like C# and Java because the
Compiler can usually inline the access.
–Note : it is a bad idea for Android.
• Virtual method calls are expensive, much more than instance field
lookups.
• Follow common object-oriented programming practices and have getters
and setters in public interface, but within a class, you should always
access fields directly
12. Best Practices for Performance
• Use Enhanced “for-each” loop for collections that
implement the Iterable interface
– With Collections, an iterator is allocated to make interface calls to
hasNext() and next()
– With an ArrayList, a hand-written count loop is about 3x faster
(with or without JIT*)
– For other collections, the enhanced for loop syntax will be exactly
equivalent to explicit iterator usage
* Performance Tips | Android Developers
(http://developer.android.com/training/articles/perf-tips.html)
13. Best Practices for Performance
• Avoid Using Floating-Point
– Generally, floating-point is about 2x slower* than integer on
Android-powered devices
– In terms of speed, there’s no difference between float and double.
However, in terms of space, double is 2x larger*. If space is not
an issue, then use double instead of float
• Do not perform “premature optimization”
– Make sure you know the problem you are trying to solve
– Be sure that you can accurately measure your existing
performance
* Based on benchmarks performed and documented in code.google.com “dalvik” project
14. Best Practices for Performance
• How to keep your application responsive to UI?
– UI does not lock-up and display an “Application Not Responding”
(ANR) dialog
– In Android, the system guards against apps that are not
responsive for a period of time by displaying a dialog indicating
that the app has stopped responding
15. Best Practices for Performance
• How to keep your application responsive to UI?
- What triggers ANR?
- ANR displays if an app cannot respond to user input (i.e. application
blocks on some I/O operation such as a network access on the UI
thread) so the system cannot process incoming user input events
- In Android, application responsiveness is monitored by the Activity
manager and Window Manager system services
- Android displays the ANR dialog when it detects
- No response to an input event (such as a key press or screen touch events)
within 5 seconds
- A BroadcastReceiver has not finished executing within 10 seconds
16. Best Practices for Performance
• How to avoid ANRs?
– Android applications normally run entirely on a single thread by
default the “UI thread” or the “main thread”.
– Any method that runs in the UI thread should do as little work as
possible on that thread
– Any long running operations such as network or database
operations or computationally expensive calculations should be
done in a worker thread or for database operations, use an
asynchronous request
– Create a worker thread for longer operations using the AsyncTask
class.
• Simply extend AsyncTask and implement the doInBackground() method
to perform the work
• To post progress changes to the user, call publishProgress() =>
onProgressUpdate() callback method
• From your implementation of onProgressUpdate() (which runs on the
UI thread) => notify the user
18. Best Practices for Performance
Execute the worker thread by simply creating an instance and
calling execute()
-You can also create your own Thread or HandlerThread class
-If you implement Thread or HandlerThread, be sure that your UI
thread does not block while waiting for the worker thread to
complete (i.e. do not call Thread.wait() or Thread.sleep()
-Instead of blocking while waiting for a worker thread to complete,
your main thread should provide a handler for the other threads to
post back to upon completion
- This will allow your app’s UI thread to remain responsive to input and
avoid ANR dialogs caused by the 5 seconds input event timeout
19. Best Practices for Performance
–Constraint on BroadcastReceiver execution time
• BroadcastReceivers are meant to do small, discrete amounts of work in
the background such as saving a setting or registering a Notification
• Applications should avoid potentially long-running operation or
calculations in a BroadcastReceiver.
• Instead of doing intensive tasks via worker threads, your application
should start an IntentService if a potentially long running action needs
to be taken in response to an intent broadcast
20. Best Practices for Performance
• Ensuring Responsiveness
• 100-200 ms is the threshold beyond which users will perceive slowness
in an application
• Additional Tips to avoid ANR and increasing your application’s perceived
performance
- If your app is doing work in the background in response to user input, show a
ProgressBar in your UI
- Do computational intensive calculations (i.e. games) in a worker thread
- If your app has a time-consuming initial setup phase, then use a Splash screen
or do rendering asynchronously
- Use performance tools (i.e. Systrace or Traceview) to determine bottlenecks
in your app’s responsiveness
21. Best Practices for User Experience
• Designing Effective Navigation
– Organize your application’s UI hierarchy and forms of navigation
so users can effectively and intuitively traverse your app content
• Designing for Multiple Screens
- Learn how to group related screens together on larger screen devices to
optimize use of available screen space
• Techniques for Descendant and Lateral Navigation
- Allowing users to navigate deep into as well as across your content hierarchy
• Techniques for Ancestral and Temporal Navigation
- Allow users to navigate upwards in the content hieararchy
- Best Practices for the Back button
- Temporal Navigation => navigation to previous screens that may not be
hierarchically related
22. Best Practices for User Experience
• Designing Effective Navigation
– Designing for Multiple Touch Screens
• Android apps need to adapt to a number of different types of devices
(3” handsets to 10” tablets to 42” TVs)
• Group Screens with Multi-pane Layouts
(Refer to Android Design’s Pane Layouts Guidelines)
- 3-4 inch screens are generally only suitable for showing a single vertical pane
of content at a time
- Larger screens such as those found on Tablet generally have more available
screen space and are able to present multiple panes of content. In landscape,
panes are usually ordered left to right in increasing detail order
- Many desktop apps and web apps offer a left-hand navigation pane or use a
Master-detail two-pane layout
23. Best Practices for User Experience
• Designing Effective Navigation
– Designing for Multiple Tablet Orientations
• Common Strategies for creating portrait tablet layouts:
Courtesy of developer.android.com/training/design-navigation/multiple-sizes.html
24. Fragments
• What is a Fragment?
– Create a dynamic and multi-pane user interface on Android, you
need to encapsulate UI components and activity behaviors into
modules that you can swap into and out of your activities.
– Fragment class allows you to create these modules
• Behaves somewhat like a nested activity that can define its own layout
and manage its own lifecycle
– Fragment can be configured in different combinations with other
fragments inside an activity to modify your layout configuration for
different screen sizes
• For instance, a small screen might show one fragment at a time, but a
large screen can show two or more.
25. Best Practices for User Experience
• Implement Back Navigation with Fragments
– When using fragments in your application, individual
FragmentTransaction objects can represent context changes that
should be added to the back stack
– Ex. If implementing a master/detail flow on a handset by
swapping out fragments (i.e. emulating a startActivity() call),
ensure that pressing the Back button on a detail screen returns
the user to the master screen. To do this, you can use
addToBackStack()
– Activity’s FragmentManager handles Back button presses if there
are FragmentTransaction objects on the back stack. When this
happens, FragmentManager pops the most recent transaction off
26. Benefits of Using Intents
• Using the Share Intent
– Works just like your own Activity
– Can pass data back and forth between applications
– Return to your Activity when closed
– Component which receives the Intent can use the
getIntent().getExtras() to get the extra data
27. Benefits of Using Intent Filters
• Use Intents to start other components
– Calling Activities
• To start an Activity, use the method startActivity(Intent). This
method is defined on the Context object and available in every Activity
object
• If you call an activity with the startActivity(Intent) method, the
caller requires no result from the called Activity
– You can also start services via intents.
• Use the startService(Intent)
28. Benefits of Using Intent Filters
• Define Intent Filters to share your functionality
– Activity Intent Filters
• Specifies the type of Intent an activity, service or Broadcast Receiver can
respond to
• Declares the capabilities of a component
• Specifies what an activity or service can do and what types of broadcasts
a Receiver can handle
– IntentFilters typically defined via the AndroidManifest.xml file
– Example: Register your Activity as Browser (triggered when
someone wants to open a web page)
29. Summary
Golden Rules & Best Practices of Performance
– Keeping your apps responsive
• What triggers ANR and how to avoid ANR?
– Running Background Services
– Improving the Performance & Scalability of long-running
operations by dispatching work to multiple threads
•Best Practices for User Experience
– Designing effective navigation
• Designing for Multiple Screens
• Designing for Multiple Tablet Orientations
– Implementing Effective Navigation
• How to correctly handle the Back button
•Benefits of Intents and Intent Filters
Whether helping to balance a checkbook, run a small business or pay income taxes, our innovative solutions have simplified millions of people ’s lives.
IFS counts as one app. native mobile apps by product titles (e.g., Weave, SnapTax) regardless of how many countries, binaries, devices, app stores or, in the case of IFS, the number of white label implementations (currently ~491).