Making Good Apps Great More Advanced Topics For Expert Android Developers
This document provides tips and techniques for developing efficient Android apps that use battery and data resources sparingly. It discusses strategies like batching network requests, prefetching only necessary data, tailoring requests based on device capabilities and connection type, and caching responses. Code samples demonstrate implementing techniques like failure backoff, inexact repeating alarms, and tracking network usage. The goal is to create reliable apps that perform well across various devices and connection scenarios.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
69 views73 pages
Making Good Apps Great More Advanced Topics For Expert Android Developers
This document provides tips and techniques for developing efficient Android apps that use battery and data resources sparingly. It discusses strategies like batching network requests, prefetching only necessary data, tailoring requests based on device capabilities and connection type, and caching responses. Code samples demonstrate implementing techniques like failure backoff, inexact repeating alarms, and tracking network usage. The goal is to create reliable apps that perform well across various devices and connection scenarios.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73
Making Good Apps Great
More advanced techniques for expert Android developers
Reto Meier Android Developer Relations Tech Lead Android Protips 2 Electric Boogaloo Reto Meier Android Developer Relations Tech Lead What if you needed your phone to !irt? 3 I dont use the Internet on my phone...
Smart phone user I dont use the Internet on my phone. Of course I use Google and Gmail. Smart phone user When Does the Internet Stop Being the Internet? 6 Invisibility E"ciency Reliability Work o!ine Be consistent but creative Know that less is more Understand not all devices are the same Apps You Dont Think About 8 MyIntentService.java 9 Queue and Send if (!isConnected) { alarms.cancel(retryQueuedCheckinsPendingIntent); pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); addToQueue(timeStamp, reference, id); } else { if (!checkin(timeStamp, reference, id)) addToQueue(timeStamp, reference, id); // Retry each of the queued checkins // Delete the queued checkins that were successful. // If there are still queued checkins then set a non-waking alarm to retry them. if (queuedCheckins.getCount() > 0) { long trigger = SystemClock.elapsedRealtime() + RETRY_INTERVAL; alarms.set(AlarmManager.ELAPSED_REALTIME, trigger, retryQueuedCheckinsPendingIntent); } } Work o!ine Be consistent but creative Know that less is more Understand not all devices are the same Apps You Dont Think About 10 http://developer.android.com/design Work o!ine Be consistent but creative Know that less is more Understand not all devices are the same Apps You Dont Think About 12 Work o!ine Be consistent but creative Know that less is more Understand not all devices are the same Apps You Dont Think About 13 Di#erent Devices, Di#erent Hardware 14 MyService.java 15 Detect Your Hardware Platform PackageManager pm = getPackageManager();
boolean hasBFCamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA); boolean hasWiFiDirect = pm.hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT); boolean hasPortScreen = pm.hasSystemFeature(PackageManager.FEATURE_SCREEN_PORTRAIT); Boost Battery Life by Enabling Airplane Mode 17 Smaller payloads Transfer less often Cache your results Using the mobile radio less 18 The Cookie Monster Dilemma 19 Many small downloads? Fewer large downloads? 20 Transfer less data across the network Store and process less data on the device Use less memory / storage / bandwidth The False Economy of the Little Cookie 21 The Big Cookie Model 22 The Mobile Radio State Machine 23 Radio Standby Radio Low Power Radio Full Power 2s latency Radio idle for seconds Radio idle for seconds 1.5s latency ~5-10 ~10-60 AT&T 3G 24 Radio Standby Radio Low Power Radio Full Power 2s latency Radio idle for seconds Radio idle for seconds 1.5s latency 5 12 Vodafone 25 Radio Standby Radio Low Power Radio Full Power 2s latency Radio idle for seconds Radio idle for seconds 1.5s latency 5 30 Normalizing Mean State Transition Times with FFTs 26 Fragmented Network Tra"c 27 0 2 4 6 8 10 12 Prefetching Batching, bundling, and preempting Reducing your number of connections Defragmenting Your Network Tra"c 28 Defragmented Network Tra"c 29 0 2 4 6 8 10 12 Same Data. Di#erent Power Pro$le. 30 21% 37% 42% 0% Active High Power Low Power Idle 12% 8% 17% 63% Logcat logging ARO tool from AT&T Network Statistics in DDMS Analyzing Network Usage 31 MyActivity.java 32 Tag your Data Transfers TrafficStats.setThreadStatsTag(0xF00D); TrafficStats.tagSocket(outputSocket);
// TODO Transfer data using socket
TrafficStats.untagSocket(outputSocket); MyActivity.java 33 Tag your Data Transfers TrafficStats.setThreadStatsTag(0xF00D); try { // Make network request using HttpClient.execute() } finally { TrafficStats.clearThreadStatsTag(); } Short Spikes 34 0 2 4 6 8 10 12 Regular / Periodic Transfers 35 0 0.2 0.4 0.6 0.8 1 1.2 Batches of Activity in Close Proximity 36 0 2 4 6 8 10 12 0 0.2 0.4 0.6 0.8 1 1.2 Latency B a t t e r y
L i f e
Battery Life versus Latency 37 A good app is like a good butler. It has what you want, before you have to ask for it. Try to download only what youll need 2 to 5 minutes of app usage 1 to 5mb of data (on a 3G network) Prefetching 39 MyService.java 40 Not All Networks Transfer Data Equally int prefetchCacheSize = DEFAULT_PREFETCH_CACHE; switch (activeNetwork.getType()) { case ConnectivityManager.TYPE_WIFI: prefetchCacheSize = MAX_PREFETCH_CACHE; break; case ConnectivityManager.TYPE_MOBILE): { switch (telephonyManager.getNetworkType()) { case TelephonyManager.NETWORK_TYPE_LTE: case TelephonyManager.NETWORK_TYPE_HSPAP: prefetchCacheSize *= 4; break; case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_GPRS: prefetchCacheSize /= 2; break; default: break; } break; } default: break; } Transfer as much as possible during each session Minimize the number of sessions Delay time-insensitive transfers Preempt scheduled transfers Batching and Preempting 41 TransferQueueSingleton.java 42 Create a Batch Queue for Periodic Transfers private Queue<MyPeriodicTransfer> updateQueue;
public synchronized void enqueuePeriodicTransfer(MyPeriodicTransfer periodicTransfer) { updateQueue.add(periodicTransfer); }
public void executeBatchedPeriodicTransfers() { // Execute the batched periodic update queue. executeBatchedPeriodicTransfersOnly(); // Preempt scheduled update executeNextPrefetch(); }
private synchronized void executeBatchedPeriodicTransfersOnly() { // TODO Bundle the received updates / requests into a single transfer. updateQueue.clear(); // TODO Upload / download the periodic transfer } TransferQueueSingleton.java 43 Trigger Pending Transfers During On Demand Updates public void executeOnDemandDownload(DownloadDetails details) { // TODO Execute an on demand download. executeNextPrefetch(); }
public void executeNextPrefetch() { // TODO Execute the next planned prefetch.
// Execute the batched periodic update queue executeBatchedPeriodicTransfersOnly(); } Minimize the Impact of Regular Transfers MyService.java 45 Inexact Repeating Alarms int alarmType = AlarmManager.ELAPSED_REALTIME; long interval = AlarmManager.INTERVAL_HOUR; long start = SystemClock.elapsedRealtime() + interval;
if (!success) { retryIn(interval*2 < MAX_RETRY_INTERVAL ? interval*2 : MAX_RETRY_INTERVAL); } } Google Cloud Messaging 50 Google Cloud Messaging 51 Available back to Android 2.2 (~94% of devices) Can transmit to multiple recipients No quota limits Tickle not transmit Next session in Room 9: Google Cloud Messaging Google Cloud Messaging 52 Redundant Downloads are Redundant MyService.java 54 Reduce Your Payloads // Non-sensitive data Context.getExternalCacheDir();
// Sandboxed application data Context.getCacheDir();
Filter on the server Rescale your images on the server Cache ALL the things! MyService.java 55 Dont Download Again Until Necessary long expires = httpURLConnection.getHeaderFieldDate("Expires", currentTime); long lastModified = httpURLConnection.getHeaderFieldDate("Last-Modified", currentTime);
// Dont refresh until at least the expiry time setDataExpirationDate(expires);
if (lastModified > lastUpdateTime) { // Parse update } MyService.java 56 Use the HttpResponseCache private void enableHttpResponseCache() { try { long httpCacheSize = 10 * 1024 * 1024; // 10 MiB File httpCacheDir = new File(getCacheDir(), "http"); Class.forName(android.net.http.HttpResponseCache") .getMethod(install", File.class, long.class) .invoke(null, httpCacheDir, httpCacheSize); } catch (Exception httpResponseCacheNotAvailable) { Log.d(TAG, "HTTP response cache is unavailable."); } } http://developer.android.com/training/e!cient-downloads Transferring Data Without Draining the Battery 57 Lint Strict Mode Test. Test. Test. Reliability 59 Bucket Testing 60 Small Normal Large Xlarge LDPI 2.3% 0.7% 0.3% MDPI 26.2% 2% 7.4% HDPI 2.4% 57.8% XHDPI 0.9% Bucket Testing 61 Small Normal Large Xlarge LDPI 2.3% 0.7% 0.3% MDPI 26.2% 2% 7.4% HDPI 2.4% 57.8% XHDPI 0.9% Bucket Testing 62 Small Normal Large Xlarge LDPI 2.3% 0.7% 0.3% MDPI 26.2% 2% 7.4% HDPI 2.4% 57.8% Nexus 7 XHDPI Galaxy Nexus HTC One X Samsung S III http://developer.android.com/guide/practices/screens_support.html Supporting Multiple Screens 63 Monkey Runner Alpha testers Emulator Stability 64 Android: Smartphones++ 66 67 68 I dont use the Internet on my phone...
I dont use the Internet on my phone. Of course I use <insert your app here>. Your users Thank You! Questions? Join the Android Developer Relations team every Wednesday, 2pm Paci"c (UTC-7) for our live O#ce Hours Q&A sessions at developers.google.com/live Graphics & animations by Pandamusk (@pandamusk) +Reto Meier | @retomeier
Python Advanced Programming: The Guide to Learn Python Programming. Reference with Exercises and Samples About Dynamical Programming, Multithreading, Multiprocessing, Debugging, Testing and More
Kubernetes: Build and Deploy Modern Applications in a Scalable Infrastructure. The Complete Guide to the Most Modern Scalable Software Infrastructure.: Docker & Kubernetes, #2
Software Containers: The Complete Guide to Virtualization Technology. Create, Use and Deploy Scalable Software with Docker and Kubernetes. Includes Docker and Kubernetes.
Docker: The Complete Guide to the Most Widely Used Virtualization Technology. Create Containers and Deploy them to Production Safely and Securely.: Docker & Kubernetes, #1