SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler offline
Android Best Practices
Anuradha Weeraman
What makes a good Android app
● Responsiveness
● Resource-conscious
● User experience and UI
● Co-exist and interact with other apps
● Follows good engineering standards
A classic
Responsiveness
● Do not block the UI thread with heavy work
● Offload them to a worker thread
● Respond to user input within 5 seconds
● Broadcast receiver must complete in 10 seconds
● User perceives “slowness” if it takes more than 200ms
● Always update the user on progress
● Avoid modal views and dialogs
● Render the main view and fill in data as it arrives
Responsiveness
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
// Do the long-running work in here
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
// This is called each time you call publishProgress()
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// This is called when doInBackground() is finished
protected void onPostExecute(Long result) {
showNotification("Downloaded " + result + " bytes");
}
}
new DownloadFilesTask().execute(url1, url2, url3);
Enable StrictMode
public void onCreate() {
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate();
}
Performance Pointers
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.
Avoid creating unnecessary objects
Performance Pointers
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.
Prefer static over virtual
Performance Pointers
When declaring constants in a class, always use ‘static
final’ as it reduces the amount of work that the VM has to
do at runtime.
Use ‘static final’ for constants
static final int intVal = 42;
static final String strVal = "Hello,
world!";
Performance Pointers
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. Virtual method calls are expensive,
much more so than instance field lookups. Direct field
access is about 7x faster than invoking a trivial getter.
Avoid internal getters/setters
i = getCount()Replace
i = mCountWith
Question time
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;
}
Place these three functions in ascending order of speed.
Performance Pointers
ARM CPUs that Android devices use do not have an FPU
and is therefore around 2x slower when performing
floating point calculations than integers as the calculation
is performed in software. Avoid using floating point
wherever possible, and keep note of this when optimizing
performance in hotspots.
Avoid using floating point
Performance Pointers
Android libraries have been extensively optimized for the
constrained runtime environment. Use the provided
libraries for best performance. For example, System.
arraycopy() is about 9x faster than a hand-coded loop in a
JIT environment.
Use the libraries
Performance Pointers
Apps that use native code from the Android NDK are not
necessarily the most performant. There’s overhead
associated with the Java-native transition and the JIT can’
t optimize across these boundaries.
As a rule of thumb, use the NDK when you have existing
codebases that you want to make available on the
Android, and not for speeding up parts of your application.
Use native methods carefully
Performance Pointers
Measure the performance of the app using ‘traceview’ and
DDMS (now Android Device Monitor).
Always measure
Resource-conscious
● Mobile devices are resource constrained environments
● Your app must play nice in this environment
● Respect user’s preferences
● The devices may not have all the hardware you need
● Release resources when you don’t need them
Question time
What is a wake lock?
Resource Pointers
A capability that can be used to drain your battery
efficiently and quickly. Always ask the question, “Do I
need to use a wake lock?”
● Use the minimum level possible, when required.
- PARTIAL_WAKE_LOCK
- SCREEN_DIM_WAKE_LOCK
- SCREEN_BRIGHT_WAKE_LOCK
- FULL_WAKE_LOCK
● Release as soon as you can
● Specify a timeout
Don’t overuse wake locks
Resource Pointers
Don’t overuse wake locks
Flag CPU Screen Keyboard
PARTIAL_WAKE_LOCK On* Off Off
SCREEN_DIM_WAKE_LOCK On Dim Off
SCREEN_BRIGHT_WAKE_LOCK On Bright Off
FULL_WAKE_LOCK On Bright Bright
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
..screen will stay on during this section..
wl.release();
Resource Pointers
The FULL_WAKE_LOCK has been deprecated in favor
the FLAG_KEEP_SCREEN_ON attribute which is better
at handling this when the user moves between apps and
requires no special permission.
Don’t overuse wake locks
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
Resource Pointers
Only transfer data in the background if it’s enabled by the
user.
Respect user preferences
boolean backgroundDataEnabled =
connectivityManager.getBackgroundDataSetting()
Note: This is deprecated on ICS and above and will
instead show getActiveNetworkInfo() as disconnected.
Resource Pointers
● By default, the service would keep restarting when
killed by the runtime
● By setting START_NOT_STICKY it would not
Allow the runtime to kill your service
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
return Service.START_NOT_STICKY;
}
}
Resource Pointers
As with activities the Android system may terminate the
process of a service at any time to save resources. For
this reason you cannot simple use a TimerTask in the
service to ensure that it is executed on a regular basis.
Use receivers and alarms to trigger your service
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
Resource Pointers
When scheduling updates, use inexact repeating alarms
that allow the system to "phase shift" the exact moment
each alarm triggers. If several alarms are scheduled to
trigger at similar times, this phase-shifting will cause them
to be triggered simultaneously, allowing each update to
piggyback on top of a single active radio state change.
Use inexact alarms
int alarmType = AlarmManager.ELAPSED_REALTIME;
long interval = AlarmManager.INTERVAL_HOUR;
long start = System.currentTimeMillis() + interval;
alarmManager.setInexactRepeating(alarmType, start, interval, pi);
Resource Pointers
● Services should only be running when needed
● Perform the activity in an AsyncTask
● Kill the service when the task is complete
Kill your own service when work is done
stopSelf()
Resource Pointers
● Explicitly specify uses-feature node in the manifest for
every hardware/software feature used in the app
● Mark essential features as required
● Mark optional features as not required
Declared required hardware and check for availability
when using them
<uses-feature android:name="android.hardware.bluetooth" />
<uses-feature android:name="android.hardware.camera" />
Resource Pointers
Check for API availability before using features
PackageManager pm = getPackageManager();
boolean hasCompass = pm.hasSystemFeature(PackageManager.
FEATURE_SENSOR_COMPASS);
if (hasCompass) {
// do things that require the compass
}
Question time
How does Google Play make use of the uses-feature
declarations?
Question time
Are permissions required anymore when the uses-feature
element is present in the manifest?
User experience & UI
● User experience should be your first priority
● Don’t copy UI paradigms from other platforms
● Respect user expectations on navigation
● The back button should always navigate back through
previously seen screens
● Navigating between application elements should be
easy and intuitive
● Use notifications judiciously - time sensitive / involves
another person
● Use dialogs for feedback, not notification
UX/UI Pointers
Respect user expectations of navigation
UX/UI Pointers
Don’t override the menu button to make it do something
other than displaying the contextual menu. It’s important
to keep the metaphors consistent to provide a good user
experience.
Don’t override the menu button
UX/UI Pointers
While it’s easy to build for just one orientation such as
portrait, there are some devices where the orientation
changes when the physical keyboard is activated. A good
user experience needs to cater to different orientations
intelligently.
Support both landscape and portrait modes
UX/UI Pointers
● Start with vector or high res
raster art
● Scale down and optimize for
supported screens and
resolutions
● Use device independent pixels
● Use fragments to re-use design
elements across different form
factors
● Optimize the layout for the
available screen real-estate
Don’t make assumptions about screen size or
resolutions
Co-exist and interact with other apps
● Your app is just one of many on
the device
● The more it gets integrated into
the ecosystem of the device, the
easier it is for the user and better
the experience
Integration Pointers
● Use intents to leverage other people’s apps
● Can pass data back and forth between applications
● Use intent filters to share functionality with other apps
● Use content providers to expose access to an app’s
content for consumption by other apps and widgets
Leverage existing apps
Follow good engineering practices
● Don’t use undocumented APIs!!
● Android comes with a number of engineering tools for
ensuring technical quality of your app
● Use these tools during development and testing to make
sure that your app follows good engineering practices
and for troubleshooting performance issues that may
degrade the user experience
Question time
Name a tool that come with the Android SDK that can be
used for performance analysis and profiling during
development?
Static / structural analysis
● Android comes with a tool called lint that can be used for
identifying and correcting structural problems with your
code
● Each detection has an associated description and
severity level so it can be prioritized
● Can be invoked directly from the command-line,
automated build system or directly from Eclipse
● Android comes with a tool
called hierarchyviewer which
is now part of the Android
Device Monitor that can be
used for analyzing layout
rendering performance
● Can be used in combination
with lint to discover and fix
performance issues that
affect responsiveness
● The Pixel Perfect window in
hierarchyviewer can be used
for getting the layout just right
Layout optimization
● ‘traceview’ is a tool that can be used for viewing
execution logs produced by an app for method profiling
purposes.
● Traces can be created from within the code or from the
DDMS tool, depending on how granular you want the
traces
Profiling
// start tracing to "/sdcard/calc.trace"
Debug.startMethodTracing("calc");
// ...
// stop tracing
Debug.stopMethodTracing();
● ‘dmtracedump’ is an alternate tool that can be used for
visualizing the call stack from trace log files
Profiling
● systrace helps you analyze how the execution of your
application fits into the larger Android environment, letting
you see system and applications process execution on a
common timeline. The tool allows you to generate highly
detailed, interactive reports from devices running Android
4.1 and higher.
● RoboGuice is a framework that brings the simplicity and
ease of Dependency Injection to Android, using Google's
own Guice library.
Dependency Injection
class AndroidWay extends Activity {
TextView name;
ImageView thumbnail;
LocationManager loc;
Drawable icon;
String myName;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = (TextView) findViewById(R.id.name);
thumbnail = (ImageView) findViewById(R.id.thumbnail);
loc = (LocationManager) getSystemService(Activity.
LOCATION_SERVICE);
icon = getResources().getDrawable(R.drawable.icon);
myName = getString(R.string.app_name);
name.setText( "Hello, " + myName );
}
}
class RoboWay extends RoboActivity {
@InjectView(R.id.name) TextView name;
@InjectView(R.id.thumbnail) ImageView thumbnail;
@InjectResource(R.drawable.icon) Drawable icon;
@InjectResource(R.string.app_name) String myName;
@Inject LocationManager loc;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name.setText( "Hello, " + myName );
}
}
Some bedtime reading
YAMBA - Yet Another Micro-
Blogging Application
Requirements
1. Build a Twitter-like micro blogging application.
2. User can view a stream of statuses fetched from a server.
3. User can update preferences to specify user’s details.
4. The statuses are fetched from the server in the background and
persisted locally.
5. The background process that fetches the statuses is started
when the device boots.
6. The background process is started and stopped depending on
the available network connectivity.
7. A timeline view shows the latest stream of statuses from local
storage.
Question time
What are the structural building blocks in Android
that can be used to build apps?
YAMBA - Yet Another Micro-
Blogging Application

Mais conteúdo relacionado

Destaque

Android best practices 2015
Android best practices 2015Android best practices 2015
Android best practices 2015Sean Katz
 
Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices Amgad Muhammad
 
Os Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual MemoryOs Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual Memorysgpraju
 
Paging and Segmentation in Operating System
Paging and Segmentation in Operating SystemPaging and Segmentation in Operating System
Paging and Segmentation in Operating SystemRaj Mohan
 

Destaque (7)

Android best practices
Android best practicesAndroid best practices
Android best practices
 
Android best practices 2015
Android best practices 2015Android best practices 2015
Android best practices 2015
 
Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices
 
Paging
PagingPaging
Paging
 
Paging and segmentation
Paging and segmentationPaging and segmentation
Paging and segmentation
 
Os Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual MemoryOs Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual Memory
 
Paging and Segmentation in Operating System
Paging and Segmentation in Operating SystemPaging and Segmentation in Operating System
Paging and Segmentation in Operating System
 

Semelhante a Android Best Practices - Thoughts from the Trenches

What's new in android M(6.0)
What's new in android M(6.0)What's new in android M(6.0)
What's new in android M(6.0)Yonatan Levin
 
Being Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentBeing Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentReto Meier
 
Google I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and JetpackGoogle I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and JetpackSunita Singh
 
Introduction to Android M
Introduction to Android MIntroduction to Android M
Introduction to Android Mamsanjeev
 
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
 Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to realityDaniel Gallego Vico
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _courseDori Waldman
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2Dori Waldman
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8Utkarsh Mankad
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011sullis
 
Prometheus and Docker (Docker Galway, November 2015)
Prometheus and Docker (Docker Galway, November 2015)Prometheus and Docker (Docker Galway, November 2015)
Prometheus and Docker (Docker Galway, November 2015)Brian Brazil
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
 
Raising ux bar with offline first design
Raising ux bar with offline first designRaising ux bar with offline first design
Raising ux bar with offline first designKyrylo Reznykov
 
Apple watch deck yodel meetup 4-16
Apple watch deck  yodel meetup 4-16Apple watch deck  yodel meetup 4-16
Apple watch deck yodel meetup 4-16Shirin Sabahi
 

Semelhante a Android Best Practices - Thoughts from the Trenches (20)

What's new in android M(6.0)
What's new in android M(6.0)What's new in android M(6.0)
What's new in android M(6.0)
 
Best practices android_2010
Best practices android_2010Best practices android_2010
Best practices android_2010
 
Being Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentBeing Epic: Best Practices for Android Development
Being Epic: Best Practices for Android Development
 
Advanced android app development
Advanced android app developmentAdvanced android app development
Advanced android app development
 
Google I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and JetpackGoogle I/O 2019 - what's new in Android Q and Jetpack
Google I/O 2019 - what's new in Android Q and Jetpack
 
Android101
Android101Android101
Android101
 
Introduction to Android M
Introduction to Android MIntroduction to Android M
Introduction to Android M
 
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
 Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
 
Stmik bandung
Stmik bandungStmik bandung
Stmik bandung
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _course
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011
 
Droidcon Paris 2015
Droidcon Paris 2015Droidcon Paris 2015
Droidcon Paris 2015
 
Prometheus and Docker (Docker Galway, November 2015)
Prometheus and Docker (Docker Galway, November 2015)Prometheus and Docker (Docker Galway, November 2015)
Prometheus and Docker (Docker Galway, November 2015)
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Raising ux bar with offline first design
Raising ux bar with offline first designRaising ux bar with offline first design
Raising ux bar with offline first design
 
Apple watch deck yodel meetup 4-16
Apple watch deck  yodel meetup 4-16Apple watch deck  yodel meetup 4-16
Apple watch deck yodel meetup 4-16
 
Android session-5-sajib
Android session-5-sajibAndroid session-5-sajib
Android session-5-sajib
 

Último

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Último (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

Android Best Practices - Thoughts from the Trenches

  • 2. What makes a good Android app ● Responsiveness ● Resource-conscious ● User experience and UI ● Co-exist and interact with other apps ● Follows good engineering standards
  • 4. Responsiveness ● Do not block the UI thread with heavy work ● Offload them to a worker thread ● Respond to user input within 5 seconds ● Broadcast receiver must complete in 10 seconds ● User perceives “slowness” if it takes more than 200ms ● Always update the user on progress ● Avoid modal views and dialogs ● Render the main view and fill in data as it arrives
  • 5. Responsiveness private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { // Do the long-running work in here protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } // This is called each time you call publishProgress() protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } // This is called when doInBackground() is finished protected void onPostExecute(Long result) { showNotification("Downloaded " + result + " bytes"); } } new DownloadFilesTask().execute(url1, url2, url3);
  • 6. Enable StrictMode public void onCreate() { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } super.onCreate(); }
  • 7. Performance Pointers 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. Avoid creating unnecessary objects
  • 8. Performance Pointers 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. Prefer static over virtual
  • 9. Performance Pointers When declaring constants in a class, always use ‘static final’ as it reduces the amount of work that the VM has to do at runtime. Use ‘static final’ for constants static final int intVal = 42; static final String strVal = "Hello, world!";
  • 10. Performance Pointers 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. Virtual method calls are expensive, much more so than instance field lookups. Direct field access is about 7x faster than invoking a trivial getter. Avoid internal getters/setters i = getCount()Replace i = mCountWith
  • 11. Question time 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; } Place these three functions in ascending order of speed.
  • 12. Performance Pointers ARM CPUs that Android devices use do not have an FPU and is therefore around 2x slower when performing floating point calculations than integers as the calculation is performed in software. Avoid using floating point wherever possible, and keep note of this when optimizing performance in hotspots. Avoid using floating point
  • 13. Performance Pointers Android libraries have been extensively optimized for the constrained runtime environment. Use the provided libraries for best performance. For example, System. arraycopy() is about 9x faster than a hand-coded loop in a JIT environment. Use the libraries
  • 14. Performance Pointers Apps that use native code from the Android NDK are not necessarily the most performant. There’s overhead associated with the Java-native transition and the JIT can’ t optimize across these boundaries. As a rule of thumb, use the NDK when you have existing codebases that you want to make available on the Android, and not for speeding up parts of your application. Use native methods carefully
  • 15. Performance Pointers Measure the performance of the app using ‘traceview’ and DDMS (now Android Device Monitor). Always measure
  • 16. Resource-conscious ● Mobile devices are resource constrained environments ● Your app must play nice in this environment ● Respect user’s preferences ● The devices may not have all the hardware you need ● Release resources when you don’t need them
  • 17. Question time What is a wake lock?
  • 18. Resource Pointers A capability that can be used to drain your battery efficiently and quickly. Always ask the question, “Do I need to use a wake lock?” ● Use the minimum level possible, when required. - PARTIAL_WAKE_LOCK - SCREEN_DIM_WAKE_LOCK - SCREEN_BRIGHT_WAKE_LOCK - FULL_WAKE_LOCK ● Release as soon as you can ● Specify a timeout Don’t overuse wake locks
  • 19. Resource Pointers Don’t overuse wake locks Flag CPU Screen Keyboard PARTIAL_WAKE_LOCK On* Off Off SCREEN_DIM_WAKE_LOCK On Dim Off SCREEN_BRIGHT_WAKE_LOCK On Bright Off FULL_WAKE_LOCK On Bright Bright PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag"); wl.acquire(); ..screen will stay on during this section.. wl.release();
  • 20. Resource Pointers The FULL_WAKE_LOCK has been deprecated in favor the FLAG_KEEP_SCREEN_ON attribute which is better at handling this when the user moves between apps and requires no special permission. Don’t overuse wake locks getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
  • 21. Resource Pointers Only transfer data in the background if it’s enabled by the user. Respect user preferences boolean backgroundDataEnabled = connectivityManager.getBackgroundDataSetting() Note: This is deprecated on ICS and above and will instead show getActiveNetworkInfo() as disconnected.
  • 22. Resource Pointers ● By default, the service would keep restarting when killed by the runtime ● By setting START_NOT_STICKY it would not Allow the runtime to kill your service @Override public int onStartCommand(Intent intent, int flags, int startId) { //TODO do something useful return Service.START_NOT_STICKY; } }
  • 23. Resource Pointers As with activities the Android system may terminate the process of a service at any time to save resources. For this reason you cannot simple use a TimerTask in the service to ensure that it is executed on a regular basis. Use receivers and alarms to trigger your service Calendar cal = Calendar.getInstance(); Intent intent = new Intent(this, MyService.class); PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0); AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); // Start every 30 seconds alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
  • 24. Resource Pointers When scheduling updates, use inexact repeating alarms that allow the system to "phase shift" the exact moment each alarm triggers. If several alarms are scheduled to trigger at similar times, this phase-shifting will cause them to be triggered simultaneously, allowing each update to piggyback on top of a single active radio state change. Use inexact alarms int alarmType = AlarmManager.ELAPSED_REALTIME; long interval = AlarmManager.INTERVAL_HOUR; long start = System.currentTimeMillis() + interval; alarmManager.setInexactRepeating(alarmType, start, interval, pi);
  • 25. Resource Pointers ● Services should only be running when needed ● Perform the activity in an AsyncTask ● Kill the service when the task is complete Kill your own service when work is done stopSelf()
  • 26. Resource Pointers ● Explicitly specify uses-feature node in the manifest for every hardware/software feature used in the app ● Mark essential features as required ● Mark optional features as not required Declared required hardware and check for availability when using them <uses-feature android:name="android.hardware.bluetooth" /> <uses-feature android:name="android.hardware.camera" />
  • 27. Resource Pointers Check for API availability before using features PackageManager pm = getPackageManager(); boolean hasCompass = pm.hasSystemFeature(PackageManager. FEATURE_SENSOR_COMPASS); if (hasCompass) { // do things that require the compass }
  • 28. Question time How does Google Play make use of the uses-feature declarations?
  • 29. Question time Are permissions required anymore when the uses-feature element is present in the manifest?
  • 30. User experience & UI ● User experience should be your first priority ● Don’t copy UI paradigms from other platforms ● Respect user expectations on navigation ● The back button should always navigate back through previously seen screens ● Navigating between application elements should be easy and intuitive ● Use notifications judiciously - time sensitive / involves another person ● Use dialogs for feedback, not notification
  • 31. UX/UI Pointers Respect user expectations of navigation
  • 32. UX/UI Pointers Don’t override the menu button to make it do something other than displaying the contextual menu. It’s important to keep the metaphors consistent to provide a good user experience. Don’t override the menu button
  • 33. UX/UI Pointers While it’s easy to build for just one orientation such as portrait, there are some devices where the orientation changes when the physical keyboard is activated. A good user experience needs to cater to different orientations intelligently. Support both landscape and portrait modes
  • 34. UX/UI Pointers ● Start with vector or high res raster art ● Scale down and optimize for supported screens and resolutions ● Use device independent pixels ● Use fragments to re-use design elements across different form factors ● Optimize the layout for the available screen real-estate Don’t make assumptions about screen size or resolutions
  • 35. Co-exist and interact with other apps ● Your app is just one of many on the device ● The more it gets integrated into the ecosystem of the device, the easier it is for the user and better the experience
  • 36. Integration Pointers ● Use intents to leverage other people’s apps ● Can pass data back and forth between applications ● Use intent filters to share functionality with other apps ● Use content providers to expose access to an app’s content for consumption by other apps and widgets Leverage existing apps
  • 37. Follow good engineering practices ● Don’t use undocumented APIs!! ● Android comes with a number of engineering tools for ensuring technical quality of your app ● Use these tools during development and testing to make sure that your app follows good engineering practices and for troubleshooting performance issues that may degrade the user experience
  • 38. Question time Name a tool that come with the Android SDK that can be used for performance analysis and profiling during development?
  • 39. Static / structural analysis ● Android comes with a tool called lint that can be used for identifying and correcting structural problems with your code ● Each detection has an associated description and severity level so it can be prioritized ● Can be invoked directly from the command-line, automated build system or directly from Eclipse
  • 40. ● Android comes with a tool called hierarchyviewer which is now part of the Android Device Monitor that can be used for analyzing layout rendering performance ● Can be used in combination with lint to discover and fix performance issues that affect responsiveness ● The Pixel Perfect window in hierarchyviewer can be used for getting the layout just right Layout optimization
  • 41. ● ‘traceview’ is a tool that can be used for viewing execution logs produced by an app for method profiling purposes. ● Traces can be created from within the code or from the DDMS tool, depending on how granular you want the traces Profiling // start tracing to "/sdcard/calc.trace" Debug.startMethodTracing("calc"); // ... // stop tracing Debug.stopMethodTracing(); ● ‘dmtracedump’ is an alternate tool that can be used for visualizing the call stack from trace log files
  • 42. Profiling ● systrace helps you analyze how the execution of your application fits into the larger Android environment, letting you see system and applications process execution on a common timeline. The tool allows you to generate highly detailed, interactive reports from devices running Android 4.1 and higher.
  • 43. ● RoboGuice is a framework that brings the simplicity and ease of Dependency Injection to Android, using Google's own Guice library. Dependency Injection class AndroidWay extends Activity { TextView name; ImageView thumbnail; LocationManager loc; Drawable icon; String myName; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name = (TextView) findViewById(R.id.name); thumbnail = (ImageView) findViewById(R.id.thumbnail); loc = (LocationManager) getSystemService(Activity. LOCATION_SERVICE); icon = getResources().getDrawable(R.drawable.icon); myName = getString(R.string.app_name); name.setText( "Hello, " + myName ); } } class RoboWay extends RoboActivity { @InjectView(R.id.name) TextView name; @InjectView(R.id.thumbnail) ImageView thumbnail; @InjectResource(R.drawable.icon) Drawable icon; @InjectResource(R.string.app_name) String myName; @Inject LocationManager loc; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name.setText( "Hello, " + myName ); } }
  • 45. YAMBA - Yet Another Micro- Blogging Application Requirements 1. Build a Twitter-like micro blogging application. 2. User can view a stream of statuses fetched from a server. 3. User can update preferences to specify user’s details. 4. The statuses are fetched from the server in the background and persisted locally. 5. The background process that fetches the statuses is started when the device boots. 6. The background process is started and stopped depending on the available network connectivity. 7. A timeline view shows the latest stream of statuses from local storage.
  • 46. Question time What are the structural building blocks in Android that can be used to build apps?
  • 47. YAMBA - Yet Another Micro- Blogging Application