SlideShare une entreprise Scribd logo
1  sur  100
Télécharger pour lire hors ligne
Revised v4Presenter
Being Epic:
Best Practices for Android Development
Reto Meier
Twitter: retomeier
?
?
?
Android Market
• Buyer support: 32
• Seller support: 29
• Including Germany, Czech Republic, and Russia!
More Downloads = More Revenue
• Paid apps
• Ad supported
• Freemium
Agenda
• The Five Deadly Sins
• The Five Glorious Virtues
• Measuring Your Success
• Two Practical Examples
The Five Deadly Sins
S L O T H
Be Fast. Be Responsive.
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
Performance Pointers
developer.android.com/guide/practices/design/performance.html
• Optimize judiciously
• Avoid creating objects
• Use native methods
• Prefer Virtual over Interface
• Prefer Static over Virtual
• Avoid internal setters and getters
• Declare constants final
• Avoid float and enums
• Use package scope with inner classes
Responsiveness
• Avoid modal Dialogues and Activities
o Always update the user on progress (ProgressBar and
ProgressDialog)
o Render the main view and fill in data as it arrives
Responsiveness
• "Application Not Responding"
o Respond to user input within 5 seconds
o Broadcast Receiver must complete in 10 seconds
• Users perceive a lag longer than 100 to 200ms
• Use Threads and AsyncTasks within Services
AsyncTask
protected Void doInBackground(Void... arg0) {
// Do time consuming processing
postProgress();
return null;
}
@Override
protected void onPostProgress(Void... arg0) {
// Update GUI with progress
}
@Override
protected void onPostExecute(Void result) {
// Update GUI on completion
}
G L U T T O N Y
Use system resources responsibly
Gluttony
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
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
What is a WakeLock?
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();
• Force the CPU to keep running
• Force the screen to stay on (or stay bright)
• Drains your battery quickly and efficiently
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
Window Managed WakeLocks
• No need for permissions
• No accidently leaving the screen from the background
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
H O S T I L I T Y
Don't fight your users
Hostility
• UX should be your #1 priority
Hostility
• User experience should be your top priority
• Respect user expectations for navigating your app
• Don't hijack the native experience
• Respect user preferences
Respect User Expectations for Navigation Flow
• The back button should always navigate back through
previously seen screens
• Always support trackball navigation
• Understand your navigation flow when entry point is a
notification or widget
• Navigating between application elements should be easy
and intuitive
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
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();
A R R O G A N C E
Don't fight the system
Arrogance
• Don't use undocumented APIs
• Seriously. 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
D I S C R I M I N A T I O N
Design for everyone
Size Discrimination
• Don't make assumptions about screen size or resolution
• Use Relative Layouts and device independent pixels
• Optimize assets for different screen resolutions
Ensuring Future Hardware Happiness
<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"/>
• Specify uses-feature node for every API you use.
• Mark essential features as required.
• Mark optional features as not required.
• Check for API existence in code.
Ensuring Future Hardware Happiness
PackageManager pm = getPackageManager();
boolean hasCompass =
pm.hasSystemFeature(
PackageManager.FEATURE_SENSOR_COMPASS);
if (hasCompass) {
// Enable things that require the compass.
}
• Specify uses-feature node for every API you use.
• Mark essential features as required.
• Mark optional features as not required.
• Check for API existence in code.
Agenda
• The Five Deadly Sins
• The Five Glorious Virtues
• Measuring Your Success
• Two Practical Examples
The Five Glorious Virtues
B E A U T Y
Hire a designer
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
G E N E R O S I T Y
Share and consume
Generosity
• Use Intents to leverage other people's apps
• Define Intent Filters to share your functionality
Using Intents to Start Other Apps
String action = "com.hotelapp.ACTION_BOOK";
String hotel = "hotel://name/" + selectedhotelName;
Uri data = Uri.parse(hotel);
Intent bookingIntent = new Intent(action, data);
startActivityForResult(bookingIntent);
• Works just like your own Activity
• Can pass data back and forth between applications
• Return to your Activity when closed
Activity Intent Filters
• 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();
}
Activity Intent Filters
U B I Q U I T Y
Be more than an icon
Ubiquity
• Create widgets
• Surface search results into the Quick Search Box
• Live Folders
• Live Wallpapers
• Expose Intent Receivers to share your functionality
• Fire notifications
U T I L I T Y
Be useful. Be interesting.
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
Agenda
• The Five Deadly Sins
• The Five Glorious Virtues
• Measuring Your Success
• Two Practical Examples
Using Analytics
User Feedback
• Haven't received a notification in weeks even though
they're turned on. HTC EVO
• Great app! HTC EVO
• SD card support anytime soon?
• This is useless and really annoying because every time
an earth quake happens it makes Ur phone ring
• Slowest app on the market.
• Boring
• Awesome totally f ing awesome!
• Great tool! I love it. Im a geologist so its great to have this
info handy.
User Feedback
• Users contradict each other
• Users don't know framework limitations
• Users can't follow instructions
• Users provide unhelpful feedback
• Users LIE
Use Analytics
• User demographics
• App usage patterns
• Exception and error reporting
• Any analytics package is supported
Google Analytics for Mobile Applications
• Track every Activity viewed
• Track settings selected
• Track exceptions and error conditions
// Start tracking
tracker.start("UA-MY_CODE-XX", this);
// Register a page view
tracker.trackPageView("/map_view");
// Send views to server
tracker.dispatch();
Agenda
• The Five Deadly Sins
• The Five Glorious Virtues
• Measuring Your Success
• Two Practical Examples
Background Updates
Don't be "That Guy"
Don't be "That Guy"
• Let the runtime kill your background Service
Let the Runtime Kill Your Service
@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);
}
• For Services that perform a single action / polling
• Reduces resource contention
Don't be "That Guy"
• Let the runtime kill your background Service
• Kill your own Service
Kill Your Own Service
• Services should only be running when needed
• Complete a task, then kill the Service
stopSelf();
@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();
}
};
Kill Your Own Service
Don't be "That Guy"
• Let the runtime kill your background Service
• Kill your own Service
• Use Alarms and Intent Receivers
Alarms and Intent Receivers
• Schedule updates and polling
• Listen for system or application events
• No Service. No Activity. No running Application.
<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);
}
}
Intent Receivers
String alarm = Context.ALARM_SERVICE;
AlarmManager am;
am = (AlarmManager)getSystemService(alarm);
Intent intent = new Intent("REFRESH_THIS");
PendingIntent op;
op = PendingIntent.getBroadcast(this, 0, intent, 0);
int type = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
long triggerTime = SystemClock.elapsedRealtime() +
interval;
am.setRepeating(type, triggerTime, interval, op);
Alarms
Don't be "That Guy"
• Let the runtime kill your background Service
• Kill your own Service
• Use Alarms and Intent Receivers
• Use inexact Alarms
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);
Don't be "That Guy"
• Let the runtime kill your background Service
• Kill your own Service
• Use Alarms and Intent Receivers
• Use inexact Alarms
• Use Cloud to Device Messaging
Cloud to Device Messaging
• Lets you push instead of poll
• Works best for targeted updates
• Perfect for updates that need to be instant
Cloud to Device Messaging
C2DM: Registering a Device
Intent registrationIntent =
new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent.putExtra("app",
PendingIntent.getBroadcast(this, 0, new Intent(), 0));
registrationIntent.putExtra("sender",
"myC2DMaccount@gmail.com");
startService(registrationIntent);
Cloud to Device Messaging
C2DM: Receiving the Device Registration ID
<receiver android:name=".C2DMReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action
android:name="com.google.android.c2dm.intent.REGISTRATION"
/>
<category android:name="com.mypackage.myAppName"/>
</intent-filter>
</receiver>
C2DM: Receiving the Device Registration ID
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
"com.google.android.c2dm.intent.REGISTRATION")) {
// Handle Registration
}
}
Cloud to Device Messaging
Cloud to Device Messaging
C2DM: Sending a Message
C2DMessaging.get(getServletContext()).
sendWithRetry(
targetRegistrationID,
userEmailAsCollapseKey,
null, null, null, null);
• Use com.google.android.C2DM project to simplify.
• Target individuals by mapping user to registration ID.
Cloud to Device Messaging
C2DM: Receiving a Message
<receiver android:name=".C2DMReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action
android:name="com.google.android.c2dm.intent.RECEIVE"
/>
<category android:name="com.mypackage.myAppName"/>
</intent-filter>
</receiver>
C2DM: Receiving a Message
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
"com.google.android.c2dm.intent.RECEIVE")) {
// Handle incoming message
}
}
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);
Location Based Services
Location Based Services
• 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'?
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);
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);
Use Criteria to Select a Location Provider
Use Criteria to Select a Location Provider
• 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
Implement a Back-off Pattern
• Use multiple Location Listeners
o Fine and coarse
o High and low frequency / distance
• Remove listeners as accuracy improves
lm.requestLocationUpdates(coarseProvider,0,0, lcourse);
lm.requestLocationUpdates(fineProvider, 0, 0, lbounce);
Location Based Services
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);
}
};
Location Based Services
E P I C (N E S S)
Be legendary
?
Epicnessicity
• Don't be satisfied with good
• Create unique solutions
• Invent new paradigms
• Leverage the hardware
• Respect your users
• Respect the system
• Think BIG!
Questions? Feedback?
• Twitter: retomeier
• Stack Overflow tag: android
• developer.android.com
Being Epic: Best Practices for Android Development

Contenu connexe

Tendances

Incremental deployment of new features
Incremental deployment of new featuresIncremental deployment of new features
Incremental deployment of new features
sullis
 

Tendances (20)

Google Glass, the GDK, and HTML5
Google Glass, the GDK, and HTML5Google Glass, the GDK, and HTML5
Google Glass, the GDK, and HTML5
 
Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1
 
Android studio
Android studioAndroid studio
Android studio
 
Optimizing Apps for Better Performance
Optimizing Apps for Better PerformanceOptimizing Apps for Better Performance
Optimizing Apps for Better Performance
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011
 
Android 3.0 Portland Java User Group 2011-03-15
Android 3.0 Portland Java User Group 2011-03-15Android 3.0 Portland Java User Group 2011-03-15
Android 3.0 Portland Java User Group 2011-03-15
 
Selendroid - Selenium for Android
Selendroid - Selenium for AndroidSelendroid - Selenium for Android
Selendroid - Selenium for Android
 
Android 3.1 - Portland Code Camp 2011
Android 3.1 - Portland Code Camp 2011Android 3.1 - Portland Code Camp 2011
Android 3.1 - Portland Code Camp 2011
 
Native Android Development with Spring
Native Android Development with SpringNative Android Development with Spring
Native Android Development with Spring
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)07.4. Android Basic Simple Browser (WebView)
07.4. Android Basic Simple Browser (WebView)
 
Google Android
Google AndroidGoogle Android
Google Android
 
Extending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScriptExtending Spring MVC with Spring Mobile and JavaScript
Extending Spring MVC with Spring Mobile and JavaScript
 
Android App development and test environment, Understaing android app structure
Android App development and test environment, Understaing android app structureAndroid App development and test environment, Understaing android app structure
Android App development and test environment, Understaing android app structure
 
Mobile Web Development with HTML5
Mobile Web Development with HTML5Mobile Web Development with HTML5
Mobile Web Development with HTML5
 
Getting started with Google Android - OSCON 2008
Getting started with Google Android - OSCON 2008Getting started with Google Android - OSCON 2008
Getting started with Google Android - OSCON 2008
 
Android N multi window
Android N multi windowAndroid N multi window
Android N multi window
 
Native Android Development Practices
Native Android Development PracticesNative Android Development Practices
Native Android Development Practices
 
Incremental deployment of new features
Incremental deployment of new featuresIncremental deployment of new features
Incremental deployment of new features
 
What's new in android jakarta gdg (2015-08-26)
What's new in android   jakarta gdg (2015-08-26)What's new in android   jakarta gdg (2015-08-26)
What's new in android jakarta gdg (2015-08-26)
 

En vedette

Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentation
connectshilpa
 
Android OS Presentation
Android OS PresentationAndroid OS Presentation
Android OS Presentation
hession25819
 
Android seminar ppt
Android seminar pptAndroid seminar ppt
Android seminar ppt
chakrapani tripathi
 

En vedette (20)

Android best practices 2015
Android best practices 2015Android best practices 2015
Android best practices 2015
 
Presentation on Android operating system
Presentation on Android operating systemPresentation on Android operating system
Presentation on Android operating system
 
Android Development: The Basics
Android Development: The BasicsAndroid Development: The Basics
Android Development: The Basics
 
Android seminar-presentation
Android seminar-presentationAndroid seminar-presentation
Android seminar-presentation
 
Android ppt
Android ppt Android ppt
Android ppt
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Efficient Android Threading
Efficient Android ThreadingEfficient Android Threading
Efficient Android Threading
 
Android OS Presentation
Android OS PresentationAndroid OS Presentation
Android OS Presentation
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Android Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App DevelopersAndroid Protips: Advanced Topics for Expert Android App Developers
Android Protips: Advanced Topics for Expert Android App Developers
 
Android seminar ppt
Android seminar pptAndroid seminar ppt
Android seminar ppt
 
Android workShop
Android workShopAndroid workShop
Android workShop
 
My presentation on Android in my college
My presentation on Android in my collegeMy presentation on Android in my college
My presentation on Android in my college
 
PPT Companion to Android
PPT Companion to AndroidPPT Companion to Android
PPT Companion to Android
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Smart Attendance Management System Using Android WIFI Technology
Smart Attendance Management System Using Android WIFI TechnologySmart Attendance Management System Using Android WIFI Technology
Smart Attendance Management System Using Android WIFI Technology
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
Android OS version history
Android OS version historyAndroid OS version history
Android OS version history
 
Android History 2015
Android History 2015Android History 2015
Android History 2015
 
Android in practice
Android in practiceAndroid in practice
Android in practice
 

Similaire à Being Epic: Best Practices for Android Development

DEFCON 18- These Aren't the Permissions You're Looking For
DEFCON 18- These Aren't the Permissions You're Looking ForDEFCON 18- These Aren't the Permissions You're Looking For
DEFCON 18- These Aren't the Permissions You're Looking For
Michael Scovetta
 
Android Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the TrenchesAndroid Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the Trenches
Anuradha Weeraman
 

Similaire à Being Epic: Best Practices for Android Development (20)

DEFCON 18- These Aren't the Permissions You're Looking For
DEFCON 18- These Aren't the Permissions You're Looking ForDEFCON 18- These Aren't the Permissions You're Looking For
DEFCON 18- These Aren't the Permissions You're Looking For
 
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
 
Android Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the TrenchesAndroid Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the Trenches
 
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
Gits class #22: [ONLINE] Analyze Your User's Activities Using BigQuery and Da...
 
Tool Development 01 - Introduction to Tool Development
Tool Development 01 - Introduction to Tool DevelopmentTool Development 01 - Introduction to Tool Development
Tool Development 01 - Introduction to Tool Development
 
Mini-Training: AngularJS
Mini-Training: AngularJSMini-Training: AngularJS
Mini-Training: AngularJS
 
Introduction to Angular JS
Introduction to Angular JSIntroduction to Angular JS
Introduction to Angular JS
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
Using Automatic Refactoring to Improve Energy Efficiency of Android Apps
Using Automatic Refactoring to Improve Energy Efficiency of Android AppsUsing Automatic Refactoring to Improve Energy Efficiency of Android Apps
Using Automatic Refactoring to Improve Energy Efficiency of Android Apps
 
All about that reactive ui
All about that reactive uiAll about that reactive ui
All about that reactive ui
 
Hybrid application development
Hybrid application developmentHybrid application development
Hybrid application development
 
Profiling tools and Android Performance patterns
Profiling tools and Android Performance patternsProfiling tools and Android Performance patterns
Profiling tools and Android Performance patterns
 
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
Сергей Жук "Android Performance Tips & Tricks"
Сергей Жук "Android Performance Tips & Tricks"Сергей Жук "Android Performance Tips & Tricks"
Сергей Жук "Android Performance Tips & Tricks"
 
Android Performance Tips & Tricks
Android Performance Tips & TricksAndroid Performance Tips & Tricks
Android Performance Tips & Tricks
 
Continuous Delivery: How RightScale Releases Weekly
Continuous Delivery: How RightScale Releases WeeklyContinuous Delivery: How RightScale Releases Weekly
Continuous Delivery: How RightScale Releases Weekly
 
GDD Japan 2009 - Designing OpenSocial Apps For Speed and Scale
GDD Japan 2009 - Designing OpenSocial Apps For Speed and ScaleGDD Japan 2009 - Designing OpenSocial Apps For Speed and Scale
GDD Japan 2009 - Designing OpenSocial Apps For Speed and Scale
 
A Taste of Monitoring and Post Mortem Debugging with Node
A Taste of Monitoring and Post Mortem Debugging with Node A Taste of Monitoring and Post Mortem Debugging with Node
A Taste of Monitoring and Post Mortem Debugging with Node
 
Uncovering breaking changes behind UI on mobile applications
Uncovering breaking changes behind UI on mobile applicationsUncovering breaking changes behind UI on mobile applications
Uncovering breaking changes behind UI on mobile applications
 

Dernier

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
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Dernier (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
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
 
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
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Being Epic: Best Practices for Android Development

  • 1.
  • 2. Revised v4Presenter Being Epic: Best Practices for Android Development Reto Meier Twitter: retomeier
  • 3. ?
  • 4. ?
  • 5. ?
  • 6.
  • 7.
  • 8. Android Market • Buyer support: 32 • Seller support: 29 • Including Germany, Czech Republic, and Russia!
  • 9. More Downloads = More Revenue • Paid apps • Ad supported • Freemium
  • 10. Agenda • The Five Deadly Sins • The Five Glorious Virtues • Measuring Your Success • Two Practical Examples
  • 12. S L O T H Be Fast. Be Responsive.
  • 13. 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
  • 14. Performance Pointers developer.android.com/guide/practices/design/performance.html • Optimize judiciously • Avoid creating objects • Use native methods • Prefer Virtual over Interface • Prefer Static over Virtual • Avoid internal setters and getters • Declare constants final • Avoid float and enums • Use package scope with inner classes
  • 15. Responsiveness • Avoid modal Dialogues and Activities o Always update the user on progress (ProgressBar and ProgressDialog) o Render the main view and fill in data as it arrives
  • 16.
  • 17. Responsiveness • "Application Not Responding" o Respond to user input within 5 seconds o Broadcast Receiver must complete in 10 seconds • Users perceive a lag longer than 100 to 200ms • Use Threads and AsyncTasks within Services
  • 18. AsyncTask protected Void doInBackground(Void... arg0) { // Do time consuming processing postProgress(); return null; } @Override protected void onPostProgress(Void... arg0) { // Update GUI with progress } @Override protected void onPostExecute(Void result) { // Update GUI on completion }
  • 19. G L U T T O N Y Use system resources responsibly
  • 20. Gluttony 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 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
  • 21. What is a WakeLock? 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(); • Force the CPU to keep running • Force the screen to stay on (or stay bright) • Drains your battery quickly and efficiently
  • 22. 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
  • 23. Window Managed WakeLocks • No need for permissions • No accidently leaving the screen from the background getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  • 24. H O S T I L I T Y Don't fight your users
  • 25. Hostility • UX should be your #1 priority
  • 26. Hostility • User experience should be your top priority • Respect user expectations for navigating your app • Don't hijack the native experience • Respect user preferences
  • 27. Respect User Expectations for Navigation Flow • The back button should always navigate back through previously seen screens • Always support trackball navigation • Understand your navigation flow when entry point is a notification or widget • Navigating between application elements should be easy and intuitive
  • 28. 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
  • 29. 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();
  • 30. A R R O G A N C E Don't fight the system
  • 31. Arrogance • Don't use undocumented APIs • Seriously. 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
  • 32. D I S C R I M I N A T I O N Design for everyone
  • 33.
  • 34.
  • 35. Size Discrimination • Don't make assumptions about screen size or resolution • Use Relative Layouts and device independent pixels • Optimize assets for different screen resolutions
  • 36.
  • 37. Ensuring Future Hardware Happiness <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"/> • Specify uses-feature node for every API you use. • Mark essential features as required. • Mark optional features as not required. • Check for API existence in code.
  • 38. Ensuring Future Hardware Happiness PackageManager pm = getPackageManager(); boolean hasCompass = pm.hasSystemFeature( PackageManager.FEATURE_SENSOR_COMPASS); if (hasCompass) { // Enable things that require the compass. } • Specify uses-feature node for every API you use. • Mark essential features as required. • Mark optional features as not required. • Check for API existence in code.
  • 39. Agenda • The Five Deadly Sins • The Five Glorious Virtues • Measuring Your Success • Two Practical Examples
  • 40. The Five Glorious Virtues
  • 41. B E A U T Y Hire a designer
  • 42.
  • 43.
  • 44. 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
  • 45. G E N E R O S I T Y Share and consume
  • 46. Generosity • Use Intents to leverage other people's apps • Define Intent Filters to share your functionality
  • 47. Using Intents to Start Other Apps String action = "com.hotelapp.ACTION_BOOK"; String hotel = "hotel://name/" + selectedhotelName; Uri data = Uri.parse(hotel); Intent bookingIntent = new Intent(action, data); startActivityForResult(bookingIntent); • Works just like your own Activity • Can pass data back and forth between applications • Return to your Activity when closed
  • 48. Activity Intent Filters • 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>
  • 49. @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(); } Activity Intent Filters
  • 50. U B I Q U I T Y Be more than an icon
  • 51. Ubiquity • Create widgets • Surface search results into the Quick Search Box • Live Folders • Live Wallpapers • Expose Intent Receivers to share your functionality • Fire notifications
  • 52. U T I L I T Y Be useful. Be interesting.
  • 53. 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
  • 54. Agenda • The Five Deadly Sins • The Five Glorious Virtues • Measuring Your Success • Two Practical Examples
  • 56. User Feedback • Haven't received a notification in weeks even though they're turned on. HTC EVO • Great app! HTC EVO • SD card support anytime soon? • This is useless and really annoying because every time an earth quake happens it makes Ur phone ring • Slowest app on the market. • Boring • Awesome totally f ing awesome! • Great tool! I love it. Im a geologist so its great to have this info handy.
  • 57. User Feedback • Users contradict each other • Users don't know framework limitations • Users can't follow instructions • Users provide unhelpful feedback • Users LIE
  • 58.
  • 59. Use Analytics • User demographics • App usage patterns • Exception and error reporting • Any analytics package is supported
  • 60. Google Analytics for Mobile Applications • Track every Activity viewed • Track settings selected • Track exceptions and error conditions // Start tracking tracker.start("UA-MY_CODE-XX", this); // Register a page view tracker.trackPageView("/map_view"); // Send views to server tracker.dispatch();
  • 61. Agenda • The Five Deadly Sins • The Five Glorious Virtues • Measuring Your Success • Two Practical Examples
  • 64. Don't be "That Guy" • Let the runtime kill your background Service
  • 65. Let the Runtime Kill Your Service @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); } • For Services that perform a single action / polling • Reduces resource contention
  • 66. Don't be "That Guy" • Let the runtime kill your background Service • Kill your own Service
  • 67. Kill Your Own Service • Services should only be running when needed • Complete a task, then kill the Service stopSelf();
  • 68. @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(); } }; Kill Your Own Service
  • 69. Don't be "That Guy" • Let the runtime kill your background Service • Kill your own Service • Use Alarms and Intent Receivers
  • 70. Alarms and Intent Receivers • Schedule updates and polling • Listen for system or application events • No Service. No Activity. No running Application.
  • 71. <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); } } Intent Receivers
  • 72. String alarm = Context.ALARM_SERVICE; AlarmManager am; am = (AlarmManager)getSystemService(alarm); Intent intent = new Intent("REFRESH_THIS"); PendingIntent op; op = PendingIntent.getBroadcast(this, 0, intent, 0); int type = AlarmManager.ELAPSED_REALTIME_WAKEUP; long interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES; long triggerTime = SystemClock.elapsedRealtime() + interval; am.setRepeating(type, triggerTime, interval, op); Alarms
  • 73. Don't be "That Guy" • Let the runtime kill your background Service • Kill your own Service • Use Alarms and Intent Receivers • Use inexact Alarms
  • 74. 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);
  • 75. Don't be "That Guy" • Let the runtime kill your background Service • Kill your own Service • Use Alarms and Intent Receivers • Use inexact Alarms • Use Cloud to Device Messaging
  • 76. Cloud to Device Messaging • Lets you push instead of poll • Works best for targeted updates • Perfect for updates that need to be instant
  • 77. Cloud to Device Messaging
  • 78. C2DM: Registering a Device Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER"); registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); registrationIntent.putExtra("sender", "myC2DMaccount@gmail.com"); startService(registrationIntent);
  • 79. Cloud to Device Messaging
  • 80. C2DM: Receiving the Device Registration ID <receiver android:name=".C2DMReceiver" android:permission="com.google.android.c2dm.permission.SEND"> <intent-filter> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="com.mypackage.myAppName"/> </intent-filter> </receiver>
  • 81. C2DM: Receiving the Device Registration ID public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( "com.google.android.c2dm.intent.REGISTRATION")) { // Handle Registration } }
  • 82. Cloud to Device Messaging
  • 83. Cloud to Device Messaging
  • 84. C2DM: Sending a Message C2DMessaging.get(getServletContext()). sendWithRetry( targetRegistrationID, userEmailAsCollapseKey, null, null, null, null); • Use com.google.android.C2DM project to simplify. • Target individuals by mapping user to registration ID.
  • 85. Cloud to Device Messaging
  • 86. C2DM: Receiving a Message <receiver android:name=".C2DMReceiver" android:permission="com.google.android.c2dm.permission.SEND"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="com.mypackage.myAppName"/> </intent-filter> </receiver>
  • 87. C2DM: Receiving a Message public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( "com.google.android.c2dm.intent.RECEIVE")) { // Handle incoming message } }
  • 89. 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); Location Based Services
  • 90. Location Based Services • 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'?
  • 91. 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);
  • 92. 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); Use Criteria to Select a Location Provider
  • 93. Use Criteria to Select a Location Provider • 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
  • 94. Implement a Back-off Pattern • Use multiple Location Listeners o Fine and coarse o High and low frequency / distance • Remove listeners as accuracy improves
  • 96. 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); } }; Location Based Services
  • 97. E P I C (N E S S) Be legendary ?
  • 98. Epicnessicity • Don't be satisfied with good • Create unique solutions • Invent new paradigms • Leverage the hardware • Respect your users • Respect the system • Think BIG!
  • 99. Questions? Feedback? • Twitter: retomeier • Stack Overflow tag: android • developer.android.com