Upload
tasneem-sayeed
View
6.294
Download
0
Tags:
Embed Size (px)
Citation preview
people
Best Practices for Mobile Application Development on Android
Tasneem Sayeed
March 15, 2013
A Leading Provider of Business and Financial Management Solutions
Intuit at a Glance
• 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
Revolutionizing People’s Lives… Solving Their Important Problems…
Creating Innovative Products and Services
Mint.comFinance
TaxCaster Finance
TurboTax SnapTaxFinance
Intuit GoPaymentBusiness
QuickBooks MobileBusiness
Online PayrollBusiness
Intuit Small Business BlogBusiness
WeaveProductivity
Online Banking forFinancial Institutions
TurboTaxFor the iPadFinance
EITC Finder Finance
Intuit HealthDebit CardFinance
Intuit Tax OnlineAccountantFinance
MoneyDueBusiness
MyTaxRefundFinance
QuickenFinance
Intuit PaperTrailBusiness
GoPatientMedical Practice
Intuit apps
SnapPayrollBusiness
MyBizTrackerBusinessiOSUK
ProFile ConnectAccountingiOSCanada
5
FORTUNE 100 Best Companies to Work For 12 Consecutive Years!
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
Agenda
•Best Practices for User Experience– Implementing Effective Navigation• How to correctly handle the Back button
•Benefits of Intents and Intent Filters
•Summary
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
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
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
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
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)
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
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
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
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
Best Practices for Performance AsyncTask Example
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
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
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
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
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
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
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.
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 the back stack and removes it if the transaction added it
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
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)
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)
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
Resources
– Android Developers• http://developer.android.com
– UI Overview - Android Developers• http://developer.android.com/design/get-started/ui-
overview.html
– Android Design Principles• http://developer.android.com/design/get-started/principles.html
– My Mobile Corner• http://mymobilecorner.blogspot.com