SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 

Kürzlich hochgeladen (20)

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 

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