Troubleshooting Android Emulator: "Emulator: Process finished with exit code 1"

Emulator: Process finished with exit code 1 You opened AVD Manager in Android Studio and tried to start an AVD, you got “Emulator: Process finished with exit code 1”. Following are the steps to debug this Find out the name of the emulator. Click the down arrow 🔽 which is to the right of play arrow ▶️, to find out the name of the AVD. Let’s say the name is “Nexus_5X_API_28_x86”. ...

Circle CI vs Travis CI

Update: As of Mar 2022, I recommend everyone to use GitHub Actions I maintain a somewhat popular Android developer tool ( adb-enhanced). The tool is written in Python, supporting both Python 2 and 3. Testing the tool requires both Python runtime as well a running Android emulator. I, initially, used Travis CI for setting up continuous testing of this tool. Later, I felt that Travis CI was too slow and when I came across Circle CI, I decided to give it a try. As of now, both Travis and Circle CI are used for testing. Here is what I learned from my experience.

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. ...

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.

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

Application Not Responding (ANR)

Demystifying Android rendering: Jank and ANR

Almost everyone developing an Android app has seen something like this in their device logs. Bash 1 I/Choreographer(1200): Skipped 60 frames! The application may be doing too much work on its main thread. On most devices, the Android platform tries to render a new frame every 16 milliseconds (60 fps). The rendering requires that whatever work is happening on the UI thread should finish in that timeframe (well, actually in less than that). Any unit of work (== Runnable) scheduled on the UI thread has to fit in that. When the work takes longer, then frames are skipped. One skipped frame is 16 ms of the hung screen. The UI looks janky and unresponsive and if the user interacts with the screen and the application does not respond in time ( 5 seconds) then Application Not Responding (ANR) shows up. ...

Built-in "Developer options" in Android

Android has a few really good settings built right into the platform for debugging under a hidden “Developer Options” menu. You can turn them on via Settings -> About Phone -> Build Number (tap 7 times). The steps will be similar but might vary a bit across OEMs. In older versions of Android, this used to be an explicit option under the Settings tab. I find the following options to be useful for the development ...