blob: 1eced64640310d2791d2775ad2aa4a1c2f82f986 [file] [log] [blame] [view]
John Field1d74b682015-09-11 21:14:09 +00001---
2layout: documentation
3---
4
5# bazel mobile-install
6
7<p class="lead">Fast iterative development for Android</p>
8
9## TL;DR
10
11To install small changes to an Android app very quickly, do the following:
12
13 1. Find the `android_binary` rule of the app you want to install.
14 2. Disable Proguard by removing the `proguard_specs` attribute.
15 3. Set the `multidex` attribute to `native`.
16 4. Set the `dex_shards` attribute to `10`.
17 5. Connect your device running ART (not Dalvik) over USB and enable USB
18 debugging on it.
19 6. Run `bazel mobile-install :your_target`. App startup will be a little
20 slower than usual.
21 7. Edit the code or Android resources.
22 8. Run `bazel mobile-install --incremental :your_target`.
23 9. Enjoy not having to wait a lot.
24
25Some command line options to Bazel that may be useful:
26
27 - `--adb` tells Bazel which adb binary to use
28 - `--adb_arg` can be used to add extra arguments to the command line of `adb`.
29 One useful application of this is to select which device you want to install
30 to if you have multiple devices connected to your workstation:
31 `bazel mobile-install --adb_arg=-s --adb_arg=<SERIAL> :your_target`
32 - `--start_app` automatically starts the app
33
34When in doubt, look at the
35[example](https://github.com/bazelbuild/bazel/tree/master/examples/android)
36or [contact us](http://bazel.io/contributing.html).
37
38## Introduction
39
40One of the most important attributes of a developer's toolchain is speed: there
41is a world of difference between changing the code and seeing it run within a
42second and having to wait minutes, sometimes hours, before you get any feedback
43on whether your changes do what you expect them to.
44
45Unfortunately, the traditional Android toolchain for building an .apk entails
46many monolithic, sequential steps and all of these have to be done in order to
47build an Android app. At Google, waiting five minutes to build a single-line
48change was not unusual on larger projects like Google Maps.
49
50`bazel mobile-install` makes iterative development for Android much faster by
51using a combination of change pruning, work sharding, and clever manipulation of
52Android internals, all without changing any of your app's code.
53
54## Problems with traditional app installation
55
56We identified the following bottlenecks of building an Android app:
57
58- Dexing. By default, "dx" is invoked exactly once in the build and it does not
59know how to reuse work from previous builds: it dexes every method again, even
60though only one method was changed.
61
62- Uploading data to the device. adb does not use the full bandwidth of a USB 2.0
63connection, and larger apps can take a lot of time to upload. The entire app is
64uploaded, even if only small parts have changed, for example, a resource or a
65single method, so this can be a major bottleneck.
66
67- Compilation to native code. Android L introduced ART, a new Android runtime,
68which compiles apps ahead-of-time rather than compiling them just-in-time like
69Dalvik. This makes apps much faster at the cost of longer installation
70time. This is a good tradeoff for users because they typically install an app
71once and use it many times, but results in slower development where an app is
72installed many times and each version is run at most a handful of times.
73
74## The approach of `bazel mobile-install`
75
76`bazel mobile-install `makes the following improvements:
77
78 - Sharded dexing. After building the app's Java code, Bazel shards the class
79 files into approximately equal-sized parts and invokes `dx` separately on
80 them. `dx` is not invoked on shards that did not change since the last build.
81
82 - Incremental file transfer. Android resources, .dex files, and native
83 libraries are removed from the main .apk and are stored in under a separate
84 mobile-install directory. This makes it possible to update code and Android
85 resources independently without reinstalling the whole app. Thus,
86 transferring the files takes less time and only the .dex files that have
87 changed are recompiled on-device.
88
89 - Loading parts of the app from outside the .apk. A tiny stub application is
90 put into the .apk that loads Android resources, Java code and native code
91 from the on-device mobile-install directory, then transfers control to the
92 actual app. This is all transparent to the app, except in a few corner cases
93 described below.
94
95### Sharded Dexing
96
97Sharded dexing is reasonably straightforward: once the .jar files are built, a
98[tool](https://github.com/bazelbuild/bazel/blob/master/src/tools/android/java/com/google/devtools/build/android/ziputils/DexMapper.java)
99shards them into separate .jar files of approximately equal size, then invokes
100`dx` on those that were changed since the previous build. The logic that
101determines which shards to dex is not specific to Android: it just uses the
102general change pruning algorithm of Bazel.
103
104The first version of the sharding algorithm simply ordered the .class files
105alphabetically, then cut the list up into equal-sized parts, but this proved to
106be suboptimal: if a class was added or removed (even a nested or an anonymous
107one), it would cause all the classes alphabetically after it to shift by one,
108resulting in dexing those shards again. Thus, we settled upon sharding not
109individual classes, but Java packages instead. Of course, this still results in
110dexing many shards if a new package is added or removed, but that is much less
111frequent than adding or removing a single class.
112
113The number of shards is controlled by the BUILD file (using the
114`android_binary.dex_shards` attribute). In an ideal world, Bazel would
115automatically determine how many shards are best, but Bazel currently must know
116the set of actions (i.e. commands to be executed during the build) before
117executing any of them, so it cannot determine the optimal number of shards
118because it doesn't know how many Java classes there will eventually be in the
119app. Generally speaking, the more shards, the faster the build and the
120installation will be, but the slower app startup becomes, because the dynamic
121linker has to do more work. The sweet spot is usually between 10 and 50 shards.
122
123### Incremental File Transfer
124
125After building the app, the next step is to install it, preferably with the
126least effort possible. Installation consists of the following steps:
127
128 1. Installing the .apk (i.e. `adb install`)
129 2. Uploading the .dex files, Android resources, and native libraries to the
130 mobile-install directory
131
132There is not much incrementality in the first step: the app is either installed
133or not. Bazel currently relies on the user to indicate if it should do this step
134through the `--incremental` command line option because it cannot determine in
135all cases if it is necessary.
136
137In the second step, the app's files from the build are compared to an on-device
138manifest file that lists which app files are on the device and their
139checksums. Any new files are uploaded to the device, any files that have changed
140are updated, and any files that have been removed are deleted from the
141device. If the manifest is not present, it is assumed that every file needs to
142be uploaded.
143
144Note that it is possible to fool the incremental installation algorithm by
145changing a file on the device, but not its checksum in the manifest. We could
146have safeguarded against this by computing the checksum of the files on the
147device, but this was deemed to be not worth the increase in installation time.
148
149### The Stub Application
150
151The stub application is where the magic to load the dexes, native code and
152Android resources from the on-device `mobile-install` directory happens.
153
154The actual loading is implemented by subclassing `BaseDexClassLoader` and is a
155reasonably well-documented technique. This happens before any of the app's
156classes are loaded, so that any application classes that are in the apk can be
157placed in the on-device `mobile-install` directory so that they can be updated
158without `adb install`.
159
160This needs to happen before any of the
161classes of the app are loaded, so that no application class needs to be in the
162.apk which would mean that changes to those classes would require a full
163re-install.
164
165This is accomplished by replacing the `Application` class specified in
166`AndroidManifest.xml` with the
167[stub application](https://github.com/bazelbuild/bazel/blob/master/src/tools/android/java/com/google/devtools/build/android/incrementaldeployment/StubApplication.java). This
168takes control when the app is started, and tweaks the class loader and the
169resource manager appropriately at the earliest moment (its constructor) using
170Java reflection on the internals of the Android framework.
171
172Another thing the stub application does is to copy the native libraries
173installed by mobile-install to another location. This is necessary because the
174dynamic linker needs the `X` bit to be set on the files, which is not possible to
175do for any location accessible by a non-root `adb`.
176
177Once all these things are done, the stub application then instantiates the
178actual `Application` class, changing all references to itself to the actual
179application within the Android framework.
180
181## Results
182
183### Performance
184
185In general, `bazel mobile-install` results in a 4x to 10x speedup of building
186and installing large apps after a small change. We computed the following
187numbers for a few Google products:
188
189<img src="/assets/mobile-install-performance.svg"/>
190
191This, of course, depends on the nature of the change: recompilation after
192changing a base library takes more time.
193
194### Limitations
195
196The tricks the stub application plays don't work in every case. We have
197identified the following cases where it does not work as expected:
198
199 - When `Context` is cast to the `Application` class in
200 `ContentProvider#onCreate()`. This method is called during application
201 startup before we have a chance to replace the instance of the `Application`
202 class, therefore, `ContentProvider` will still reference the stub application
203 instead of the real one. Arguably, this is not a bug since you are not
204 supposed to downcast `Context` like this, but this seems to happen in a few
205 apps at Google.
206
207 - Resources installed by `bazel mobile-install` are only available from within
208 the app. If resources are accessed by other apps via
209 `PackageManager#getApplicationResources()`, these resources will be from the
210 last non-incremental install.
211
212 - Devices that aren't running ART. While the stub application works well on
213 Froyo and later, Dalvik has a bug that makes it think that the app is
214 incorrect if its code is distributed over multiple .dex files in certain
215 cases, for example, when Java annotations are used in a
216 [specific](https://code.google.com/p/android/issues/detail?id=78144) way. As
217 long as your app doesn't tickle these bugs, it should work with Dalvik, too
218 (note, however, that support for old Android versions isn't exactly our
219 focus)