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 - https://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 ...

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

Thoughts on Tizen

Users won’t buy a phone till they know that their basic set of apps is available on the device. That pretty much rules out players like BlackBerry 10 , Jolla , Ubuntu OS , and Firefox OS . Even Microsoft is still struggling . OEMs like Samsung, HTC, LG, and Sony have been hit hard by the commoditization of Android. Google makes money from Google Play, cheaper phones imply more users. So, the commoditization of Android OEMs is good for Google. These OEMs have to customize Android as per Google’s requirements which have increased over time. They cannot manufacture a competing version of Android (like Amazon’s Fire Phone) either. This leaves us with iOS and Google-experience Android duopoly. The only way to break that duopoly is Samsung, which is big enough that it can convince major developers to develop apps for its devices and throw money at marketing to reach out to end users. It can make money from selling devices as well as selling apps (via the app store). A completely open-source OS can pull open-source developers from GNU/Linux and Android to develop it. A completely open-source OS can convince other OEMs to use it and in lieu, they can partner with Samsung on app store revenue sharing. It remains to see what Tizen’s delayed launch eventually leads to, but it’s a matter of survival for Samsung. ...

Android command-line: gradle and testing

For android projects, some engineers use Android Studio (new), some use Eclipse with ADT (old), few like me still savor command line, this blog post is about handling (building, installing and testing) android projects from command line. To create android project Sh 1 2 $ android create project --target 4 --name TestAndroidApp --path ./test_android_app --activity Main --package net.ashishb.TestAndroidApp --gradle --gradle-version 1.0.+&nbsp; ... After changing to directory test_android_app (cd test_android_app), fix a bug ...

How to start locale settings activity on android from command-line

A useful and handy command specially when you during experimentation, you are stuck because of a changing language settings to an undecipherable foreign language. Bash 1 2 3 adb shell am start -n \ 'com.android.settings/.Settings\$LocalePickerActivity'

Android, Gradle and compile-time only dependencies

Android plugin for Gradle does not support Java-style compile time only dependencies. After spending a few hours on trying to build android app targeted for Amazon SDK (without using Amazon’s Android specific plugin but just their jar stubs for maps, ADM and Home widget), I finally found that the one way to support compile-time dependencies is following. For application project Groovy 1 2 3 4 5 6 7 8 9 10 11 12 13 configurations { provided } dependencies { // ... provided fileTree(dir: "${project.rootDir}/path_to_libs_dir", include: '*.jar') } // Android's version of sourceSets.main.compileClasspath android.applicationVariants.each { variant -> variant.javaCompile.classpath += configurations.provided } For the library project Groovy 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 configurations { provided } dependencies { // ... compile fileTree(dir: 'libs', include: '*.jar') provided fileTree(dir: "${project.rootDir}/patch_to_libs_dir", include: '*.jar') } android.libraryVariants.all { variant -> // Exclude the jar files from making its way into the final apk. // Irrespective of what the path_to_libs_dir is the final jar files end up in libs dir. variant.packageLibrary.exclude('libs/lib1.jar') variant.packageLibrary.exclude('libs/lib2.jar') // ... } References https://stackoverflow.com/questions/16613722/gradle-configurations-not-working-as-expected-in-new-android-build-system https://stackoverflow.com/a/24157721

How to compile android emulator on ubuntu 13.10

I was trying to make some modifications to android emulator and was unable to find good set of instructions for the compiling the same. Here are mine. Bash 1 2 3 4 5 6 7 8 9 10 11 12 13 14 # Get the source code. git clone https://android.googlesource.com/platform/external/qemu cd qemu # Install required dependencies. sudo apt-get install gcc-multilib libesd0-dev libx11-dev \ libxext-dev libasound2-dev libpulse-dev \ lib32stdc++-4.8-dev # Install ia32 libraries (missing from default ubuntu 13.10). sudo apt-get install libgtk2.0-0:i386 libpangox-1.0-0:i386 \ libpangoxft-1.0-0:i386 libidn11:i386 libglu1-mesa:i386 # Configure and build the emulator binary. ./android-configure.sh --no-gles --no-tests --cc=/usr/bin/gcc make -j16 # The emulator binaries are in objs directory.