Android: Fragment related pitfalls and how to avoid them

Don’t use platform fragments ( android.app.Fragment), they have been deprecated and can trigger version-specific bugs. Use the support library fragments ( android.support.v4.app.Fragment) instead. A Fragment is created explicitly via your code or recreated implicitly by the FragmentManager. The FragmentManager can only recreate a Fragment if it’s a public non-anonymous class. To test for this, rotate your screen while the Fragment is visible. FragmentTransaction#commit can fail if the activity has been destroyed. “java.lang.IllegalStateException: Activity has been destroyed” Why - This can happen in the wild where say right before FragmentTransaction#commit() executes, the user gets a phone call and your activity is backgrounded and destroyed. How to trigger manually - The easy way to manually test this is to add a call to Activity#finish() right before FragmentTransaction#commit. Fix - Before doing FragmentTransaction#commit(), check that the activity has not been destroyed - Activity#isDestroyed() should return false. ...

Android: Handling JPEG images with Exif orientation flags

A JPEG file can have Exif metadata which can provide the rotation/translation field information for a raw JPEG image. So, a landscape raw JPEG image could actually be a portrait because it’s EXIF orientation could be set to ORIENTATION_ROTATE_90, the best way to handle such scenarios is to either use a library like Picasso or Glide or at least learn from them. Here is a piece of code from Picasso which loads a JPEG as an in-memory bitmap and performs the right translation/rotation. ...

Mac OS: App Translocation and Android Studio updates failure

I installed Android Studio via homebrew “brew cask install android-studio” as a part of my automated Mac OS setup. Recently, Android Studio prompted me that an update is available. When I accepted to update, it failed with an error “Studio does not have write access to /private/var/folders/wt/rjv6_wcn4f97_2nth7fqftqh0000gn/T/AppTranslocation/19A80F28-865B-41FC-AA87-B8E43C826FCB/d/Android Studio.app/Contents. Please run it by a privileged user to update.” This error was confusing; I was running Android Studio as myself, a nonprivileged user and the same user owned this directory. Googling it a bit for AppTranslocation took me here. ...

Cross-language bridge error handling: JS-to-Java Example

All languages have certain semantics for dealing with error cases. C deals with them by setting error codes. Java deals with them by throwing exceptions. JavaScript deals with them by throwing exceptions as well but unlike Java, it does have any concept of checked Exceptions. The JS interpreter just stops. And this has some interesting implications in hybrid scenarios like a Webview based app. Consider a simple Android app where most of the code is in JavaScript but is making a request to Java layer. ...

Testing resumable uploads

The core idea behind resumable upload is straightforward if you are uploading a big file, then you are going to encounter users in the network conditions where they cannot upload the file in a single network session. The client-side code, to avoid restarting the file upload from the beginning, must figure out what portion of the file was uploaded and “resume” the upload of the rest. How to do resumable upload Before starting the upload, send a unique ID generated from the file contents to the server like MD-5 or SHA-256. The server decides and declares what the format of that unique ID is. Next, the server responds with an offset which indicates how many bytes server already has. The client uploads rest of the bytes with a Content-Range header. ...

Architecting Android apps for emerging markets

This is a long post. It covers several decisions like API version, distribution beyond play store, UI & network performance, and minimizing RAM, disk, and battery usage.

Introducing adb-enhanced: A swiss army knife for Android development

Android development requires tons of disconnected approaches for development and testing. Consider some scenarios To test runtime permission - Go to Settings -> Applications -> Application info of the app you are looking for and disable that permission. To test a fresh install - adb shell pm clear-data com.example To test your app under the battery-saver mode - turn on the battery saver mode by expanding the notification bar To stop the execution of an app - kill it via activity manager, adb shell am kill com.example To test your app under doze mode - first, make the device believe that it is unplugged via “adb shell dumpsys battery unplug”, then, make it think that it is discharging via “adb shell dumpsys battery set status 3”, and then enable doze mode via “adb shell dumpsys deviceidle force-idle”. And don’t forget to execute a set of unrelated complementary commands once you are done to bring the device back to its normal state. To see the overdraw of the app - Go to the developer options and enable/disable it there. Over time, this became a significant mental burden that I first wrote some of these flows in a text file and then converted them to automated shell scripts. But when even that felt insufficient, I created a tool for myself called adb-enhanced. ...

Google I/O 2018: Android Notes

Highlights All android support library code is moving to the androidx namespace. No more android.support.v4 or android. support.v7 namespaces. Android app bundle to split the app into downloadable modules Navigation library to set up navigation between different activities/fragments. Use WorkManager for background work - this is an improvement to JobScheduler Major improvements to Android Studio. Most standalone tools were deprecated in favor of adding the same functionality into Android Studio. Major improvements to Android Vitals which in Google Play to learn more about what’s going on with the Android app’s performance. Android P does more profiling to improve code locality for faster execution. Modern Android Development hierarchy viewer is replaced by ViewTree in Android Studio TraceView is replaced by Systrace in Android Studio Profiler (DDMS) is replaced by Android Profiler in Android Studio Dalvik is replaced by ART Java is replaced by Kotlin as a preferred language Layouts Absolute Layout - deprecated Linear Layout - still OK Frame Layout - still OK Grid Layout - discouraged Relative Layout - discouraged ConstraintLayout - recommended ListView, GridView, and Gallery are deprecated. RecyclerView is recommended with ListAdapter for updations. Platform Fragments (android.app.fragments) are deprecated. Support library fragments are recommended. Single activity app recommended Rather than managing activity lifecycle use Lifecycle to observe state changes Rather than keeping plain data with views, use LiveData to update views automatically. Use ViewModel to deal with screen rotation. Room is recommended in place of SQLite CursorAdapter and AsyncListUtil are discouraged. Use Paging instead with a neat, graceful offline use-case handling trick. Don’t do manual bitmap management. Use Glide, Picasso, or Lottie instead. Between TextureView and SurfaceView, use SurfaceView. Nine patches are discouraged. Use Vector Drawables. Use FusedLocationProviderClient for fetching the device location. Wi-Fi access triangulation is coming to Android P. FusedLocationProvider will eventually add support for that for indoor location tracking. MediaPlayer is discouraged, use ExoPlayer instead. A detailed hands-on presentation on ExoPlayer Performance 42% of 1-star reviews mention crashes/bugs ANR/crash rate reduces engagement - use StrictMode to catch them early Avoid IPC on the main thread, StrictMode won’t catch the violation, and you would never know what’s happening on the other side of the IPC call which can block the main thread If BroadcastReceiver#onReceive is going to take more than 10 seconds, then call goAsync for background processing and call PendingResult#onFinish() once that’s finished WakeLocks - avoid using them. All except PARTIAL_WAKE_LOCK are deprecated with Android P. Use FLAG_KEEP_SCREEN_ON for keeping the screen on in an activity Use WorkManager for background work Use AlarmManager for short-interval callback enums are not discouraged anymore. Platform code avoids it but unlike in prior Android versions, the penalty for enums is low now. A good introduction to Android’s display rendering A good introduction to Android’s text handling Text handling issues Only framework spans can be parceled, don’t mix custom spans with framework spans since only the frameworks will be part of the copied text After ~250 spans or more, SpannableStringBuilder ends up being more performant than SpannableString since the former internally uses trees. Metrics affecting spans cause measure-layout-draw calls, while appearance affecting spans cause layout-draw calls, therefore, the former is more expensive. Text measurement takes a lot of time on the UI thread, consider creating PrecomputedText on the background thread. android:autoLink = true works via RegEx and has bad performance. Consider using Linkify on the background thread. Android P also supports deep learning-based TextClassifier which is also invoked on the background thread. Testing your app for background restriction - adb shell apps set <package name> RUN_ANY_IN_BACKGROUND ignore # applies background restriction (change “ignore” to “allow” to remove restriction) Next Billion Users 28% of searches in India are voice searches 2-wheeler mode added to Google Maps Google Tez uses Ultrasound for pairing and sending money to the nearby receiver Files Go - Folder-based hierarchy won’t work for users who have never had a PC before. Therefore, shows photos based on associations like “WhatsApp Images” or “Camera”. Supports P2P file sharing for fast transfers. Design for next billion users - http://design.google/nbu Android Go 25% of devices in 2018 shipped with <= 1GB RAM (target for Android Go) Every 6 MB app size reduces the installation rate by 1% India - largest market for Go. The USA - is the second-largest market for Go. 5 seconds cold start goal Users opt for smaller apk sizes with a lower rating. The average apk size is 30 MB. Go recommends a 40MB max app size for non-game and 65MB for game apps. MLKit On-device + cloud APIs. On-device APIs are free. Firebase supports downloading models and even doing A/B testing. Experimental support to convert TensorFlow models to TensorFlow Lite models. Compiler D8 - new Dexer, now default. Enable/disable via “android.enableD8 = true/false” R8 - new optimizer, now default replacing proguard, still opt-in in 3.2. Enable via android.enableR8 = true Kotlin - talk can be here Use properties instead of default getters/setters Use data classes to generate equals, hash method, etc. Use default args instead of method overloading Use top-level functions as well as local functions (function inside functions for better encapsulation Use function extensions to make the code more readable, eg. extend String class with isDigit to be able to later write the code like “1234”.isDigit Use smart casts Use sealed classes for a superclass which should not be extendable beyond the compile-time Use string interpolation in println, eg. println(“name is ${name}”) Use val (read-only values) by default, only use var (read-write var iable) when there is a strong reason Declare lambda functions as inline to remove the cost of having an extra class Use co-routines via async instead of creating new threads Use suspend + async to convert callbacks into more readable synchronously written code

Android: The right way to pull SQLite database

Let’s say you are developing an Android app com.example.android and want to access its database file named “content” from the test device/emulator. To access this file, located in app’s database directory, on both rooted and unrooted device would be Bash 1 2 3 4 5 $ APP_NAME=com.example.android $ adb shell run-as $APP_NAME cp databases/content.db /sdcard/content.db && $ adb pull /sdcard/content.db content.db && $ adb shell rm /sdcard/content.db ... This seems to work but is incorrect. An SQLite database can have write-ahead logging (-wal) file, a journal (-journal), and shared memory (-shm) file. Anytime, you copy just the .db file; you might get an old copy of the database, the right way to copy is to copy all the four files, so that, the SQLite on the laptop displays the combined result. ...

Google I/O 2017: Android Notes

Infrastructure - Architecture & Performance Android Vitals - More visibility in Google Play dev console on battery drain, wakelocks being held for too long, ANRs, crashes, dropped frames, and frozen frames. Architecture components - better handling of the lifecycle, Room (ORM for Sqlite), live data observers. The API looks clunky though. Performance 50% 1-star reviews mention stability & bugs. 60% 5-star reviews mention speed, design, or reliability. Apps with > 5% crash rate have 30% higher uninstall rate. Emerging Markets > 100M users came online in 2016. 1B 2G devices expected in 2020. 50% of India is on 2G 33% users run out of storage in India every day. Data is expensive - it costs ~$2 to download a 40MB free app in India 53% users abandon websites if it takes more than 3 seconds to load Action items ...