Tag Archives: aosp

Order Files in Android

Posted by Aditya Kumar – Software Engineer


Binary layout using a symbol order file (also known as binary order file or linker order file) is a well-known link-time optimization. The linker uses the order of symbols in order file to lay out symbols in the binary. Order file based binary layout improves application launch time as well as other critical user journeys. Order file generation is typically a multi-step process where developers use different tools at every stage. We are providing a unified set of tools and documentation that will allow every native app developer to leverage this optimization. Both Android app developers and the AOSP community can benefit from the tools.


Source code is typically structured to facilitate software development and comprehension. The layout of functions and variables in a binary is also impacted by their relative ordering in the source code. The binary layout impacts application performance as the operating system has no way of knowing which symbols will be required in future and typically uses spatial locality as one of the cost models for prefetching subsequent pages.

But the order of symbols in a binary may not reflect the program execution order. When an application executes, fetching symbols that are not present in memory would result in page faults. For example, consider the following program:

// Test.cpp
int foo() { /* */ } int bar() { /* */ } // Other functions... int main() { bar(); foo();


Which gets compiled into:

# Test.app page_x: _foo page_y: _bar # Other symbols page_z:_main

When Test.app starts, its entrypoint _main is fetched first then _bar followed by _foo. Executing Test.app can lead to page faults for fetching each function. Compare this to the following binary layout where all the functions are located in the same page (assuming the functions are small enough).

# Test.app page_1: _main page_1: _bar page_1: _foo # Other symbols

In this case when _main gets fetched, _bar and _foo can get fetched in the memory at the same time. In case these symbols are large and they are located in consecutive pages, there is a high chance the operating system may prefetch those pages resulting in less page faults.

Because execution order of functions during an application lifecycle may depend on various factors it is impossible to have a unique order of symbols that is most efficient. Fortunately, application startup sequence is fairly deterministic and stable in general. And it is also possible to build a binary having a desired symbol order with the help of linkers like lld which is the default linker for Android NDK toolchain.

Order file is a text file containing a list of symbols. The linker uses the order of symbols in order file to lay out symbols in the binary. An order file having functions that get called during the app startup sequence can reduce page faults resulting in improved launch time. Order files can improve the launch time of mobile applications by more than 2%. The benefits of order files are more meaningful on larger apps and lower end devices. A more mature order file generation system can improve other critical user journeys.


The order file generation involves the following steps

    • Collect app startup sequence using compiler instrumentation technique
      • Use compiler instrumentation to report every function invocation
      • Run the instrumented binary to collect launch sequence in a (binary) profraw file
    • Generate order file from the profraw files
    • Validate order file
    • Merge multiple order files into one
    • Recompile the app with the merged order file


The order file generation is based on LLVM’s compiler instrumentation process. LLVM has a stage to generate the order file then recompile the source code using the order file.ALT TEXT

Collect app startup sequence

The source code is instrumented by passing -forder-file-instrumentation to the compiler. Additionally, the -orderfile-write-mapping flag is also required for the compiler to generate a mapping file. The mapping file is generated during compilation and it is used while processing the profraw file. The mapping file shows the mapping from MD5 hash to function symbol (as shown below).

# Mapping file MD5 db956436e78dd5fa main MD5 83bff1e88ac48f32 _GLOBAL__sub_I_main.cpp MD5 c943255f95351375 _Z5mergePiiii MD5 d2d2238cf08db816 _Z9mergeSortPiii MD5 11ed18006e729e73 _Z4partPiii MD5 3e897b5ee8bebbd1 _Z9quickSortPiii

The profile (profraw file) is generated every time the instrumented application is executed. The profile data in the profraw file contains the MD5 hash of the functions executed in chronological order. The profraw file does not have duplicate entries because each function only outputs its MD5 hash on first invocation. A typical run of binary containing the functions listed in the mapping file above can have the following profraw entries.

# Profraw file 00000000 32 8f c4 8a e8 f1 bf 83 fa d5 8d e7 36 64 95 db |2...........6d..| 00000010 16 b8 8d f0 8c 23 d2 d2 75 13 35 95 5f 25 43 c9 |.....#..u.5._%C.| 00000020 d1 bb be e8 5e 7b 89 3e 00 00 00 00 00 00 00 00 |....^{.>........| 00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|

In order to find the function names corresponding to the MD5 hashes in a profraw file, a corresponding mapping file is used.

Note: The compiler instrumentation for order files (-forder-file-instrumentation) only works when an optimization flag (01, 02, 03, 0s, 0z) is passed. So, if -O0 (compiler flag typically used for debug builds) is passed, the compiler will not instrument the binary. In principle, one should use the same optimization flag for instrumentation that is used in shipping release binaries.

The Android NDK repository has scripts that automate the order file generation given a mapping file and an order file.

Recompiling with Order File

Once you have an order file, you provide the path of the order file to the linker using the --symbol-ordering-file flag.

Detailed design

Creating Order File Build Property

The Android Open Source Project (AOSP) uses a build system called soong so we can leverage this build system to pass the flags as necessary. The order file build property has four main fields:

    • instrumentation
    • load_order_file
    • order_file_path
    • cflags

The cflags are meant to add other necessary flags (like mapping flags) during compilation. The load_order_file and order_file_path tells the build system to recompile with the order file rather than set it to the profiling stage. The order files must be in saved in one of two paths:

    • toolchain/pgo-profiles/orderfiles
    • vendor/google_data/pgo_profile/orderfiles

# Profiling orderfile: { instrumentation: true, load_order_file: false, order_file_path: "", cflags: [ "-mllvm", "-orderfile-write-mapping=<filename>-mapping.txt", ], } #Recompiling with Order File orderfile: { instrumentation: true, load_order_file: true, order_file_path: "<filename>.orderfile", }

Creating order files

We provide a python script to create an order file from a mapping file and a profraw file. The script also allows removing a particular symbol or creating an order file until a particular symbol.

Script Flags:

        • Profile file (--profile-file):
                • Description: The profile file generated by running a binary compiled with -forder-file-instrumentation
        • Mapping file (--mapping-file):
                • Description: The mapping file generated during compilation that maps MD5 hashes to symbol names
        • Output file (--output):
                • Description: The output file name for the order file. Default Name: default.orderfile
        • Deny List (--denylist):
                • Description: Symbols that you want to exclude from the order file
        • Last symbol (--last-symbol):
                • Description: The order file will end at the passed last symbol and ignore the symbols after it. If you want an order file only for startup, you should pass the last startup symbol. Last-symbol has priority over leftover so we will output until the last symbol and ignore the leftover flag.
        • Leftover symbols (--leftover):
                • Description: Some symbols (functions) might not have been executed so they will not appear in the profile file. If you want these symbols in your order file, you can use this flag and it will add them at the end.

Validating order files

Once we get an order file for a library or binary, we need to check if it is valid based on a set of criteria. Some order files may not be of good quality so they are better discarded. This can happen due to several reasons like application terminated unexpectedly, the runtime could not write the complete profraw file before exiting, an undesired code-sequence was collected in the profile, etc. To automate this process, we provide a python script that can help developers check for:

    • Partial order that needs to be in the order file
    • Symbols that have to be present in order file
    • Symbols that should not be present in order file
    • Minimum number of symbols to make an order file

Script Flags:

        • Order file (--order-file):
                • Description: The order file you are validating on the below criteria.
        • Partial Order (--partial):
                • Description: A partial order of symbols that must be held in the order file.
        • Allowed Lists (--allowlist):
                • Description: Symbols that must be present in the order file.
        • Denied Lists (--denylist):
                • Description: Symbols that should not be in the order file. Denylist flag has priority over allowlist.
        • Minimum Number of Entries (--min):
                • Description: Minimum number of symbols needed for an order file

Merging orderfiles

At a higher level, the order file symbols in a collection of order files approximate a partial order (poset) of function names with order defined by time of execution. Across different runs of an application, the order files might have variations. These variations could be due to OS, device class, build version, user configurations etc. However, the linker can only take one order file to build an application. In order to have one order file that provides the desired benefits, we need to merge these order files into a single order file. The merging algorithm also needs to be efficient so as to not slow down the build time. There are non-linear clustering algorithms that may not scale well for merging large numbers of order files, each having many symbols. We provide an efficient merging algorithm that converges quickly. The algorithm allows for customizable parameters, such that developers can tune the outcome.

Merging N partial order sets can be done either pessimistically (merging a selection of order files all the way until there is one order file left) or optimistically (merging all of them at once). The pessimistic approach can be inefficient as well as sub-optimal. As a result, it is better to work with all N partial order sets at once. In order to have an efficient implementation it helps to represent all N posets with a weighted directed Graph (V,E) where:

    • V: Elements of partial order sets (symbols) and the number of times it appears in different partial order sets. Note that the frequency of vertices may be greater than the sum of all incoming edges because of invocations from uninstrumented parts of binary, dependency injection etc.
    • E (V1 -> V2): An edge occurs if the element of V2 immediately succeeds V1 in any partial order set with its weight being the number of times this happens.

For a binary executable, there is one root (e.g., main) vertex, but shared libraries might have many roots based on which functions are called in the binary using them. The graph gets complicated if the application has threads as they frequently result in cycles. To have a topological order, cycles are removed by preferring the highest probability path over others. A Depth-First traversal that selects the highest weighted edge serves the purpose.

Removing Cycles:

- Mark back edges during a Depth-First traversal - For each Cycle (c):      - Add the weights of all in-edges of each vertex (v) in the cycle excluding the edges in the cycle      - Remove the cycle edge pointing **to** the vertex with highest sum

After cycles are removed, the same depth first traversal gives a topological order (the order file) when all the forward edges are removed. Essentially, the algorithm computes a minimum-spanning-tree of maximal weights and traverses the tree in topological order.

Producing an order:

printOrderUtil(G, n, order):    - If n was visited:         - return    - Add n to the end of order    - Sort all out edges based on weight    - For every out_edge (n, v):        - printOrderUtil(G, v, order) printOrder(G):    - Get all roots    - order = []    - For each root r:        - printOrderUtil(G, r, order)    - return order


Given the following order files:

    • main -> b -> c -> d
    • main -> a -> c
    • main -> e -> f
    • main -> b
    • main -> b
    • main -> c -> b
Flow diagram of orderfiles

The graph to the right is obtained by removing cycles.

    • DFS: main -> b-> c -> b
    • Back edge: c -> b
    • Cycle: b -> c-> b
    • Cycle edges: [b -> c, c -> b]
    • b’s sum of in-edges is 3
    • c’s sum of in-edges is 2
    • This implies b will be traversed from a higher frequency edge, so c -> b is removed
    • Ignore forward edges a->c, main->c
    • The DFS of the acyclic graph on the right will produce an order file main -> b -> c -> d -> a -> e -> f after ignoring the forward edges.

Collecting order files for Android Apps (Java, Kotlin)

The order file instrumentation and profile data collection is only enabled for C/C++ applications. As a result, it cannot benefit Java or Kotlin applications. However, Android apps that ship compiled C/C++ libraries can benefit from order file.

To generate order file for libraries that are used by Java/Kotlin applications, we need to invoke the runtime methods (called as part of order file instrumentation) at the right places. There are three functions that users have to call:

    • __llvm_profile_set_filename(char *f): Set the name of the file where profraw data will be dumped.
    • __llvm_profile_initialize_file: Initialize the file set by __llvm_profile_set_filename
    • __llvm_orderfile_dump: Dumps the profile(order file data) collected while running instrumented binary

Similarly, the compiler and linker flags should be added to build configurations. We provide template build system files e.g, CMakeLists.txt to compile with the correct flags and add a function to dump the order files when the Java/Kotlin application calls it.

# CMakeLists.txt set(GENERATE_PROFILES ON) #set(USE_PROFILE "${CMAKE_SOURCE_DIR}/demo.orderfile") add_library(orderfiledemo SHARED orderfile.cpp) target_link_libraries(orderfiledemo log) if(GENERATE_PROFILES) # Generating profiles require any optimization flag aside from -O0. # The mapping file will not generate and the profile instrumentation does not work without an optimization flag. target_compile_options( orderfiledemo PRIVATE -forder-file-instrumentation -O2 -mllvm -orderfile-write-mapping=mapping.txt ) target_link_options( orderfiledemo PRIVATE -forder-file-instrumentation ) target_compile_definitions(orderfiledemo PRIVATE GENERATE_PROFILES) elseif(USE_PROFILE) target_compile_options( orderfiledemo PRIVATE -Wl,--symbol-ordering-file=${USE_PROFILE} -Wl,--no-warn-symbol-ordering ) target_link_options( orderfiledemo PRIVATE -Wl,--symbol-ordering-file=${USE_PROFILE} -Wl,--no-warn-symbol-ordering ) endif()

We also provide a sample app to dump order files from a Kotlin application. The sample app creates a shared library called “orderfiledemo” and invokes the DumpProfileDataIfNeeded function to dump the order file. This library can be taken out of this sample app and can be repurposed for other applications.

// Order File Library #if defined(GENERATE_PROFILES) extern "C" int __llvm_profile_set_filename(const char *); extern "C" int __llvm_profile_initialize_file(void); extern "C" int __llvm_orderfile_dump(void); #endif void DumpProfileDataIfNeeded(const char *temp_dir) { #if defined(GENERATE_PROFILES) char profile_location[PATH_MAX] = {}; snprintf(profile_location, sizeof(profile_location), "%s/demo.output", temp_dir); __llvm_profile_set_filename(profile_location); __llvm_profile_initialize_file(); __llvm_orderfile_dump(); __android_log_print(ANDROID_LOG_DEBUG, kLogTag, "Wrote profile data to %s", profile_location); #else __android_log_print(ANDROID_LOG_DEBUG, kLogTag, "Did not write profile data because the app was not " "built for profile generation"); #endif } extern "C" JNIEXPORT void JNICALL Java_com_example_orderfiledemo_MainActivity_runWorkload(JNIEnv *env, jobject /* this */, jstring temp_dir) { DumpProfileDataIfNeeded(env->GetStringUTFChars(temp_dir, 0)); }

# Kotlin Application class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) runWorkload(applicationContext.cacheDir.toString()) binding.sampleText.text = "Hello, world!" } /** * A native method that is implemented by the 'orderfiledemo' native library, * which is packaged with this application. */ external fun runWorkload(tempDir: String) companion object { // Used to load the 'orderfiledemo' library on application startup. init { System.loadLibrary("orderfiledemo") } } }


order file generation only works for native binaries. The validation and merging scripts will work for any set of order files.


External References

Android 13 is in AOSP!

Posted by Seang Chau, VP of Engineering
Today we’re pushing the Android 13 source to the Android Open Source Project (AOSP) and officially releasing the newest version of Android. For developers, Android 13 is focused on our core themes of privacy and security as well as developer productivity, making it easier for you to build great experiences for users. We’ve also continued to make Android an even better OS for tablets and large screens, giving you better tools to take advantage of the 270+ million of these devices in use across the world. 

Android 13 is rolling out to Pixel devices starting today. Later this year, Android 13 will also roll out to more of your favorite devices from Samsung Galaxy, Asus, HMD (Nokia phones), iQOO, Motorola, OnePlus, Oppo, Realme, Sharp, Sony, Tecno, vivo, Xiaomi and more.

As always, we thank you for the feedback you’ve shared, and we appreciate the work you’ve done to make your apps compatible with today’s release. Your support and contributions are what make Android a great platform for everyone!

What’s in Android 13 for developers?

Here’s a look at some of what’s new in Android 13 - make sure to check out the Android 13 developer site for details on all of the new features.

Developer productivity and tools

Themed app icons - Android 13 extends Material You dynamic color to all app icons, letting users opt-in to icons that inherit the tint of their wallpaper and other theme preferences. All your app needs to supply is a monochromatic app icon and a tweak to the adaptive icon XML. More here.

Themed app icons adapting to wallpapers colors and dark theme (left).

Per-app language preferences - Android 13 makes it easier to support multilingual users who want to use your apps in a language that’s different from the system language. Android now provides a standard “App language” Settings panel for apps that have opted-in, and you can call a new platform API to get or set the user’s preferred locale at runtime, helping to reduce boilerplate code and improve compatibility. More here.

Per-app languages in Settings

Improved text support - Android 13 includes text and language improvements that help you deliver a more polished experience. Faster hyphenation optimizes hyphenation performance by as much as 200% so you can now enable it in your TextViews with almost no impact on rendering performance. Text conversion APIs make searching and autocompletion faster when using phonetic lettering input for languages like Japanese, Chinese, and others. Android 13 also improves line heights for non-latin scripts (such as Tamil, Burmese, Telugu, and Tibetan), eliminating clipping and making them easier to read. More here.

Improved line height for non-Latin scripts in apps targeting Android 13 (bottom).

Color vector fonts - Android 13 adds rendering support for COLR version 1 (spec, intro video) fonts and updates the system emoji to the COLRv1 format. COLRv1 is a new, highly compact, font format that renders quickly and crisply at any size. For most apps this will just work, and the system handles everything. More here.

COLRv1 vector emoji (left) and bitmap emoji.

Quick Settings Placement API - For apps that provide custom Quick Settings tiles, Android 13 makes it easier for users to discover and add your tiles. Using a new tile placement API, your app can now prompt the user to directly add your custom Quick Settings tile in a single step, without leaving your app. More here.

Programmable shaders - Android 13 introduces programmable RuntimeShader objects, with behavior defined using the Android Graphics Shading Language (AGSL). You can use these shaders to create ripple, blur, stretch, and similar advanced effects in your apps. More here.

Media controls derived from PlaybackState - For apps targeting Android 13, the system now derives media controls from PlaybackState actions, providing a richer set of controls that are consistent across phones and tablet devices and align with other Android platforms such as Android Auto and Android TV. More here.

Android 13 media controls are consistent on phones and tablets.

Bluetooth LE Audio - Low Energy (LE) Audio is the next-generation wireless audio built to enable new use cases like sharing and broadcasting audio to friends and family, or subscribing to public broadcasts for information, entertainment, or accessibility. It’s designed to ensure that users can receive high fidelity audio without sacrificing battery life, and lets them seamlessly switch between different use cases. Android 13 adds built-in support for LE Audio, so developers can use the new capabilities on compatible devices. More here.

MIDI 2.0 - Android 13 adds support for the new MIDI 2.0 standard, including the ability to connect MIDI 2.0 hardware through USB. This updated standard offers features such as increased resolution for controllers, better support for non-Western intonation, and more expressive performance using per-note controllers. More here.

OpenJDK 11 updates - Android 13 Core Libraries now align with the OpenJDK 11 LTS release, with both library updates and Java 11 programming language support for app and platform developers. We plan to bring these Core Library changes to more devices through Google Play system updates, as part of an ART module update for devices running Android 12 and higher. More here.

Predictive back gesture - Android 13 introduces new APIs that let your app tell the system that it will handle back events in advance, a practice we call the "ahead-of-time" model. This new approach is part of a multi-year effort to help you prepare your app to support the predictive back gesture, which is available for testing in this release through a developer option. More here.

Built for tablets

Android 13 extends the 12L update that we released earlier this year, and it delivers an even better experience on tablets. You’ll find features like an enhanced multitasking taskbar, more large-screen layouts and optimizations in system UI and apps, improved compatibility modes for apps, and more. We’re continuing to invest to give you the tools you need to build great experiences for tablets as well as Chromebooks and foldables. You can learn more about how to get started optimizing for large screens, and be sure to check out our large screens developer resources.

Multitasking on tablets with Android 13.

Privacy and security

Photo picker and APIs - A new system photo picker now gives users a standard, privacy-protecting way to share local and cloud-based photos. Photo picker extends Android’s long-standing document picker and makes it easy for users to share specific photos and videos with an app, without giving the app permission to view all media files on the device. Photo picker provides a dedicated experience for photos and videos and includes APIs for apps to access the shared media files. The photo picker experience is now available to users who receive Google Play system updates, on devices (excepting Go devices) running Android 11 and higher. More here.

Photo picker lets users share specific photos and videos with an app.

Notification permission - To help users focus on the notifications that are most important to them, Android 13 introduces a new notifications runtime permission. Apps now need to request the notification permission from the user before posting notifications. For apps targeting Android 12 or lower, the system will handle the upgrade flow on your behalf. More here.

Notification permission dialog in Android 13.

Nearby device permission for Wi-Fi - Android 13 introduces the NEARBY_WIFI_DEVICES runtime permission for apps that manage a device's connections to nearby access points over Wi-Fi. The new permission is required for many commonly-used Wi-Fi APIs and enables apps to discover and connect to nearby devices over Wi-Fi without also needing to acquire the location permission. More here.

Granular permissions for media file access - Photo picker is our recommended solution for user-friendly, permissionless sharing of photos and videos, but for apps that haven’t moved to photo picker yet or for audio use cases, Android 13 adds new granular media permissions. These new permissions replace the READ_EXTERNAL_STORAGE permission and provide access to specific types of media files, including images, video, or audio. We highly recommend moving your app to photo picker if possible; otherwise, use the granular media permissions when targeting Android 13. More here.
Requesting permission to access audio files.

Developer downgradable permissions - Starting in Android 13, apps that no longer require permissions previously granted by the user can use a new API to downgrade the permissions. By removing unused permissions, your app can show that it’s using the minimum permissions needed, which can improve user trust. More here.

Safer exported Intent filters - Android 13 applies stricter rules when delivering explicit intents to exported intent filters in another app that’s targeting Android 13. For intents that specify actions, the system now delivers the intents to the exported component only if the intent matches the receiver’s declared <intent-filter> elements. More here.

Performance for apps

Android 13 improves performance and efficiency for all apps through updates to the ART runtime. We plan to bring these improvements to more Android users through Google Play system updates, as part of our ongoing ART module updates for devices running Android 12 and higher.

Improved garbage collection - A new garbage collector based on the Linux kernel feature userfaultfd is coming to ART on Android 13 devices in an upcoming Google Play system update. The new garbage collector eliminates the read barrier and its fixed overhead per object loaded, reducing memory pressure and leading to as much as ~10% reduction in compiled code size. It’s more efficient at GC-time as well, since pages are freed as compaction progresses. Overall, the new garbage collector helps to save battery, avoid jank during GC operations, and protect apps from low-memory kills.

Optimizations throughout ART - In Android 13, ART makes switching to and from native code much faster, with JNI calls now up to 2.5x faster. We’ve also reworked the runtime’s reference processing to make it mostly non-blocking, which further reduces jank. We’ve exposed a new public API, Reference.refersTo(), which is useful in reclaiming unreachable objects sooner, and we’ve made the interpreter faster by optimizing class/method lookups. Lastly, ART now performs more byte-code verification at install time, avoiding the expense of verification at runtime and keeping app startup times fast. More here.

Get your apps ready!

Now with today’s public release of Android 13 to AOSP, we’re asking all Android developers to finish your compatibility testing and publish your updates as soon as possible, to give your users a smooth transition to Android 13.

To test your app for compatibility, just install it on a device running Android 13 and work through the app flows looking for any functional or UI issues. Review the Android 13 behavior changes for all apps first, to focus on areas where your current app could be affected. Here are some of the top changes to test:

  • Notifications runtime permission - Make sure you understand how this new permission works with your app’s notifications, and plan on targeting Android 13 (API 33) as soon as possible to help support users. More here.
  • Clipboard preview - Make sure your app hides sensitive data in Android 13’s new clipboard preview, such as passwords or credit card information. More here.
  • JobScheduler prefetch - JobScheduler now tries to anticipate the next time your app will be launched and will run any associated prefetch jobs ahead of that time. If you use prefetch jobs, test that they are working as expected. More here.
Remember to test the libraries and SDKs in your app for compatibility. If you find any SDK issues, try updating to the latest version of the SDK or reaching out to the developer for help.

Once you’ve published the compatible version of your current app, you can start the process to update your app's targetSdkVersion. Review the behavior changes for apps targeting Android 13 for this, and use the compatibility framework to help detect issues quickly.

Tablet and large-screens support

With Android 13 bringing a better experience to tablets, make sure your apps look their best. You can test large-screen features by setting up an Android emulator in Android Studio, or you can use a large screen device from our Android 13 Beta partners. Here are some areas to watch for:

  • Taskbar interaction - Check how your app responds when viewed with the new taskbar on large screens. Make sure your app's UI isn't cut off or blocked by the taskbar. More here.
  • Multi-window mode - Multi-window mode is now enabled by default for all apps, regardless of app configuration, so make sure the app handles split-screen appropriately. You can test by dragging and dropping your app into split-screen mode and adjusting the window size. More here.
  • Improved compatibility experience - if your app isn’t optimized for tablets yet, such as using a fixed orientation or not being resizable, check how your app responds to compatibility mode adjustments such as letterboxing. More here.
  • Media projection - If your app uses media projection, check how your app responds while playing back, streaming, or casting media on large screens. Be sure to account for device posture changes on foldable devices as well. More here.
  • Camera preview - For camera apps, check how your camera preview UI responds on large screens when your app is constrained to a portion of the screen in multi-window or split-screen mode. Also check how your app responds when a foldable device's posture changes. More here.
You can read more about the tablet features in Android 13 and what to test here.

What’s next?

Android 13 is rolling out to Pixel devices starting today.

If you’re currently enrolled in the Android Beta program, you’ll get the Android 13 final release and remain enrolled to receive ongoing Beta updates for Android 13 feature drops, starting later this year. If you’d like to opt out of ongoing Beta updates without needing to wipe your device, just visit the Android Beta site and opt out after you get the Android 13 final release and before taking the first beta for Android 13 feature drops.

System images for Pixel devices are available here for manual download and flash, and you can get the latest Android Emulator system images via the SDK Manager in Android Studio. If you're looking for the Android 13 source, you'll find it here in the Android Open Source Project repository under the Android 13 branches.

Thanks again for participating in our program of early previews and Betas! We're looking forward to seeing your apps on Android 13!

Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Welcome Android Open Source Project (AOSP) to the Bazel ecosystem

After significant investment in understanding how best to build the Android Platform correctly and quickly, we are pleased to announce that the Android Platform is migrating from its current build systems (Soong and Make) to Bazel. While components of Bazel have been already checked into the Android Open Source Project (AOSP) source tree, this will be a phased migration over the next few Android releases which includes many concrete and digestible milestones to make the transformation as seamless and easy as possible. There will be no immediate impact to the Android Platform build workflow or the existing supported Android Platform Build tools in 2020 or 2021. Some of the changesto support Android Platform builds are already in Bazel, such as Bazel’s ability to parse and execute Ninja files to support a gradual migration.

Migrating to Bazel will enable AOSP to:
  • Provide more flexibility for configuring the AOSP build (better support for conditionals)
  • Allow for greater introspection into the AOSP build progress and dependencies
  • Enable correct and reproducible (hermetic) AOSP builds
  • Introduce a configuration mechanism that will reduce complexity of AOSP builds
  • Allow for greater integration of build and test activities
  • Combine all of these to drive significant improvements in build time and experience
The benefits of this migration to the Bazel community are:
  • Significant ongoing investment in Bazel to support Android Platform builds
  • Expansion of the Bazel ecosystem and community to include, initially, tens of thousands of Android Platform developers and Android handset OEMs and chipset vendors.
  • Google’s Bazel rules for building Android apps will be open sourced, used in AOSP, and maintained by Google in partnership with the Android / Bazel community
  • Better Bazel support for building Android Apps
  • Better rules support for other languages used to build Android Platform (Rust, Java, Python, Go, etc)
  • Strong support for Bazel Long Term Support (LTS) releases, which benefits the expanded Bazel community
  • Improved documentation (tutorials and reference)
The recent check-in of Bazel to AOSP begins an initial pilot phase, enabling Bazel to be used in place of Ninja as the execution engine to build AOSP. Bazel can also explore the AOSP build graph. We're pleased to be developing this functionality directly in the Bazel and AOSP codebases. As with most initial development efforts, this work is experimental in nature. Remember to use the currently supported Android Platform Build System for all production work.

We believe that these updates to the Android Platform Build System enable greater developer velocity, productivity, and happiness across the entire Android Platform ecosystem.

By Joe Hicks on behalf of the Bazel and AOSP infrastructure teams

Turning it up to 11: Android 11 for developers

Posted by Stephanie Cuthbertson, Director, Product Management

Android 11 logo

Android 11 is here! Today we’re pushing the source to the Android Open Source Project (AOSP) and officially releasing the newest version of Android. We built Android 11 with a focus on three themes: a People-centric approach to communication, Controls to let users quickly get to and control all of their smart devices, and Privacy to give users more ways to control how data on devices is shared. Read more in our Keyword post.

For developers, Android 11 has a ton of new capabilities. You’ll want to check out conversation notifications, device and media controls, one-time permissions, enhanced 5G support, IME transitions, and so much more. To help you work and develop faster, we also added new tools like compatibility toggles, ADB incremental installs, app exit reasons API, data access auditing API, Kotlin nullability annotations, and many others. We worked to make Android 11 a great release for you, and we can’t wait to see what you’ll build!

Watch for official Android 11 coming to a device near you, starting today with Pixel 2, 3, 3a, 4, and 4a devices. To get started, visit the Android 11 developer site.

People, Controls, Privacy


Android 11 is people-centric and expressive, reimagining the way we have conversations on our phones, and building an OS that can recognize and prioritize the most important people in our lives. For developers, Android 11 helps you build deeper conversational and personal interactions into your apps.

  • Conversation notifications appear in a dedicated section at the top of the shade, with a people-forward design and conversation specific actions, such as opening the conversation as a bubble, creating a conversation shortcut on the home screen, or setting a reminder.
  • Bubbles - Bubbles help users keep conversations in view and accessible while multitasking on their devices. Messaging and chat apps should use the Bubbles API on notifications to enable this in Android 11.
  • Consolidated keyboard suggestions let Autofill apps and Input Method Editors (IMEs) securely offer users context-specific entities and strings directly in an IME’s suggestion strip, where they are most convenient for users.
mobile display of conversation UI

Bubbles and people-centric conversations.


Android 11 lets users quickly get to and control all of their smart devices in one space. Developers can use new APIs to help users surface smart devices and control media:

  • Device Controls make it faster and easier than ever for users to access and control their connected devices. Now, by simply long pressing the power button, they’re able to bring up device controls instantly, and in one place. Apps can use a new API to appear in the controls. More here.
  • Media Controls make it quick and convenient for users to switch the output device for their audio or video content, whether it be headphones, speakers or even their TV. More here.
Device controls on mobile device Media controls on mobile device

Device controls and media controls.


In Android 11, we’re giving users even more control and transparency over sensitive permissions and working to keep devices more secure through faster updates.

One-time permission - Now users can give an app access to the device microphone, camera, or location, just for one time. The app can request permissions again the next time the app is used. More here.

Permission notification

One-time permission dialog in Android 11.

Background location - Background location now requires additional steps from the user beyond granting a runtime permission. If your app needs background location, the system will ensure that you first ask for foreground location. You can then broaden your access to background location through a separate permission request, and the system will take the user to Settings to complete the permission grant.

Also note that in February we announced that Google Play developers will need to get approval to access background location in their app to prevent misuse. We're giving developers more time to make changes and won't be enforcing the policy for existing apps until 2021.

Permissions auto-reset - if users haven’t used an app for an extended period of time, Android 11 will “auto-reset” all of the runtime permissions associated with the app and notify the user. The app can request the permissions again the next time the app is used. More here.

Scoped storage - We’ve continued our work to better protect app and user data on external storage, and made further improvements to help developers more easily migrate. More here.

Google Play system updates - Launched last year, Google Play system updates help us expedite updates of core OS components to devices in the Android ecosystem. In Android 11, we more than doubled the number of updatable modules, including 12 new modules that will help improve privacy, security, and consistency for users and developers.

BiometricPrompt API - Developers can now use the BiometricPrompt API to specify the biometric authenticator strength required by their app to unlock or access sensitive parts of the app. For backward compatibility, we’ve just added these capabilities to the Jetpack Biometric library. We’ll share further updates as the work progresses.

Identity Credential API - This will unlock new use cases such as mobile drivers licences, National ID, and Digital ID. We’re working with various government agencies and industry partners to make sure that Android 11 is ready for digital-first identity experiences.

You can read about all of the Android 11 privacy features here.

Helpful innovation

Enhanced 5G support - Android 11 includes updated developer support to help you take advantage of the faster speeds and lower latency of 5G networks. You can learn when the user is connected to a 5G network, check whether the connection is metered, and get an estimate of the connection bandwidth. To help you build experiences now for 5G, we’ve also added 5G support in the Android Emulator. To get started with 5G on Android, visit the 5G developer page.

image of Google Maps on mobile

Moving beyond the home, 5G can for example let you enhance your “on-the-go” experience by providing seamless interactions with the world around you from friends and family to businesses.

New screen types - Device makers are continuing to innovate by bringing exciting new device screens to market, such as hole-punch and waterfall screens. Android 11 adds support for these in the platform, with APIs to let you optimize your apps. You can manage both hole-punch and waterfall screens using the existing display cutout APIs. You can set a new window layout attribute to use the entire waterfall screen, and a new waterfall insets API helps you manage interaction near the edges.

Call screening support - Android 11 helps call-screening apps do more to manage robocalls. Apps can verify an incoming call’s STIR/SHAKEN status (standards that protect against caller ID spoofing) as part of the call details, and they can report a call rejection reason. Apps can also customize a system-provided post call screen to let users perform actions such as marking a call as spam or adding to contacts.

Polish and quality

OS resiliency - In Android 11 we’ve made the OS more dynamic and resilient as a whole by fine-tuning memory reclaiming processes, such as forcing user-imperceptible restarts of processes based on RSS HWM thresholds. Also, to improve performance and memory, Android 11 adds Binder caching, which optimizes highly used IPC calls to system services by caching data for those that retrieve relatively static data. Binder caching also improves battery life by reducing CPU time.

Synchronized IME transitions - New APIs let you synchronize your app’s content with the IME (input method editor, or on-screen keyboard) and system bars as they animate on and offscreen, making it much easier to create natural, intuitive and jank-free IME transitions. For frame-perfect transitions, a new WindowInsetsAnimation.Callback API notifies apps of per-frame changes to insets while the system bars or the IME animate. Additionally, you can use a new WindowInsetsAnimationController API to control system UI types like system bars, IME, immersive mode, and others. More here.

Synchronized IME transition through insets animation listener. App-driven IME experience through WindowInsetsAnimationController.

Synchronized IME transition through insets animation listener.

App-driven IME experience through WindowInsetsAnimationController.

HEIF animated drawables - The ImageDecoder API now lets you decode and render image sequence animations stored in HEIF files, so you can make use of high-quality assets while minimizing impact on network data and APK size. HEIF image sequences can offer drastic file-size reductions for image sequences when compared to animated GIFs.

Native image decoder - New NDK APIs let apps decode and encode images (such as JPEG, PNG, WebP) from native code for graphics or post processing, while retaining a smaller APK size since you don’t need to bundle an external library. The native decoder also takes advantage of Android’s process for ongoing platform security updates. See the NDK sample code for examples of how to use the APIs.

Low-latency video decoding in MediaCodec - Low latency video is critical for real-time video streaming apps and services like Stadia. Video codecs that support low latency playback return the first frame of the stream as quickly as possible after decoding starts. Apps can use new APIs to check and configure low-latency playback for a specific codec.

Variable refresh rate - Apps and games can use a new API to set a preferred frame rate for their windows. Most Android devices refresh the display at 60Hz refresh rate, but some support multiple refresh rates, such as 90Hz as well as 60Hz, with runtime switching. On these devices, the system uses the app’s preferred frame rate to choose the best refresh rate for the app. The API is available in both the SDK and NDK. See the details here.

Dynamic resource loader - Android 11 includes a new public API to let apps load resources and assets dynamically at runtime. With the Resource Loader framework you can include a base set of resources in your app or game and then load additional resources, or modify the loaded resources, as needed at runtime.

Neural Networks API (NNAPI) 1.3 - We continue to add ops and controls to support machine learning on Android devices. To optimize common use-cases, NNAPI 1.3 adds APIs for priority and timeout, memory domains, and asynchronous command queue. New ops for advanced models include signed integer asymmetric quantization, branching and loops, and a hard-swish op that helps accelerate next-generation on-device vision models such as MobileNetV3.

Developer friendliness

App compatibility tools - We worked to minimize compatibility impacts on your apps by making most Android 11 behavior changes opt-in, so they won’t take effect until you change the apps’ targetSdkVersion to 30. If you are distributing through Google Play, you’ll have more than a year to opt-in to these changes, but we recommend getting started testing early. To help you test, Android 11 lets you enable or disable many of the opt-in changes individually. More here.

App exit reasons - When your app exits, it’s important to understand why the app exited and what the state was at the time -- across the many device types, memory configurations, and user scenarios that your app runs in. Android 11 makes this easier with an exit reasons API that you can use to request details of the app’s recent exits.

Data access auditing - data access auditing lets you instrument your app to better understand how it accesses user data and from which user flows. For example, it can help you identify any inadvertent access to private data in your own code or within any SDKs you might be using. More here.

ADB Incremental - Installing very large APKs with ADB (Android Debug Bridge) during development can be slow and impact your productivity, especially those developers working on Android Games. With ADB Incremental in Android 11, installing large APKs (2GB+) from your development computer to an Android 11 device is up to 10x faster. More here.

Kotlin nullability annotations - Android 11 adds nullability annotations to more methods in the public API. And, it upgrades a number of existing annotations from warnings to errors. These help you catch nullability issues at build time, rather than at runtime. More here.

Get your apps ready for Android 11

With Android 11 on its way to users, now is the time to finish your compatibility testing and publish your updates.

Flow chart steps for getting your apps ready for Android 11.

Here are some of the top behavior changes to watch for (these apply regardless of your app’s targetSdkVersion):

  • One-time permission - Users can now grant single-use permission to access location, device microphone and camera. More here.
  • External storage access - Apps can no longer access other apps’ files in external storage. More here.
  • Scudo hardened allocator - Scudo is now the heap memory allocator for native code in apps. More here.
  • File descriptor sanitizer - Fdsan is now enabled by default to detect file descriptor handling issues for native code in apps. More here.

Android 11 also includes opt-in behavior changes - these affect your app once it’s targeting the new platform. We recommend assessing these changes as soon as you’ve published the compatible version of your app. For more information on compatibility testing and tools, check out the resources we shared for Android 11 Compatibility week and visit the Android 11 developer site for technical details.

Enhance your app with new features and APIs

Next, when you're ready, dive into Android 11 and learn about the new features and APIs that you can use. Here are some of the top features to get started with.

We recommend these for all apps:

  • Dark theme (from Android 10) - Make sure to provide a consistent experience for users who enable system-wide dark theme by adding a Dark theme or enabling Force Dark.
  • Gesture navigation (from Android 10) - Support gesture navigation by going edge-to-edge and ensure that custom gestures work well with gestures. More here.
  • Sharing shortcuts (from Android 10) - Apps that want to receive shared data should use the sharing shortcuts APIs to create share targets. Apps that want to send shared data should make sure to use the system share sheet.
  • Synchronized IME transitions - Provide seamless transitions to your users using the new WindowInsets and related APIs. More here.
  • New screen types - for devices with hole-punch or waterfall screens, make sure to test and adjust your content for these screens as needed. More here.

We recommend these if relevant for your app:

  • Conversations - Messaging and communication apps can participate in the conversation experience by providing long-lived sharing shortcuts and surfacing conversations in notifications. More here.
  • Bubbles - Bubbles are a way to keep conversations in view and accessible while multitasking. Use the Bubbles API on notifications to enable this.
  • 5G - If your app or content can benefit from the faster speeds and lower latency of 5G, explore our developer resources to see what you can build.
  • Device controls - If your app supports external smart devices, make sure those devices are accessible from the new Android 11 device controls area. More here.
  • Media controls - For media apps, we recommend supporting the Android 11 media controls so users can manage playback and resumption from the Quick Settings shade. More here.

Read more about all of the Android 11 features at developer.android.com/11.

Coming to a device near you!

Android 11 will begin rolling out today on select Pixel, OnePlus, Xiaomi, OPPO and realme phones, with more partners launching and upgrading devices over the coming months. If you have a Pixel 2, 3, 3a, 4, or 4a phone, including those enrolled in this year’s Beta program, watch for the over-the-air update arriving soon!

Android 11 factory system images for Pixel devices are also available through the Android Flash Tool, or you can download them here. As always, you can get the latest Android Emulator system images via the SDK Manager in Android Studio. For broader testing on other Treble-compliant devices, Generic System Images (GSI) are available here.

If you're looking for the Android 11 source code, you'll find it here in the Android Open Source Project repository under the Android 11 branches.

What’s next?

We’ll soon be closing the preview issue tracker and retiring open bugs logged against Developer Preview or Beta builds, but please keep the feedback coming! If you still see an issue that you filed in the preview tracker, just file a new issue against Android 11 in the AOSP issue tracker.

Thanks again to the many developers and early adopters who participated in the preview program this year! You gave us great feedback to help shape the release, and you filed thousands of issues that have made Android 11 a better platform for everyone.

We're looking forward to seeing your apps on Android 11!

Flashing Builds from the Android Open Source Project

Posted by Mitchell Wills, Android Build Software Engineer

AOSP has been around for a while, but flashing builds onto a development device has always required a number of manual steps. A year ago we launched Android's Continuous Integration Dashboard, which gives more visibility into the continuous build status of the AOSP source tree. However, these builds were not available for phones and flashing devices still required a manual command line process.

In order to support developers working in AOSP we are launching Android Flash Tool, which allows developers to flash devices with builds listed on the Continuous Integration Dashboard. This can be used by developers working on the Android OS to test changes or App developers to test compatibility with the latest AOSP build.

installing build

A device being flashed.

Android Flash Tool allows anyone to use a browser supporting WebUSB, such as Chrome 79 or Edge 79, to flash an Android device entirely from the browser (Windows requires installing a driver). After connecting a device and authorizing the page to connect to it users will be presented with a list of available builds. After choosing a build click flash and the tool does the rest. You can flash recent Pixel devices and the HiKey reference boards with builds based on aosp-master.

Try Android Flash Tool yourself at https://flash.android.com.

Find out more at https://source.android.com/setup/contribute/flash.

Code Search with Cross References for the Android Open Source Project

Posted by Jeff Bailey, AOSP Engineering Manager; Ally Sillins, AOSP Program Manager; Kris Hildrum, Open Source Code Search Tech Lead; Jay Sachs, Kythe Tech Lead/Manager
Android Screenshot
Searching for "it's all about the code" open source on Google returns more than a million hits. Today we’re introducing a public code search tool for the Android Open Source Project (AOSP).
Link: https://cs.android.com
The Android repository is made up of a collection of git repositories which are managed together using our ‘repo’ tool. Because of this, most tools (such as github, gitweb, etc) can’t see the source code the way that it’s laid out when it’s checked out on the system. In partnership with our colleagues who run Google’s internal Code Search and Kythe, we’re pleased to present a code search tool that presents a view of all of the Android source code as you actually use it.
Here are some features you can take advantage of starting today:
  • View the source code
  • Navigate cross-references across the entire code base that allow you to click through one part of the source code to another
  • Switch between Android’s open source branches (not all branches will have cross-reference information)
  • View tool documentation on https://source.android.com/setup/contribute/code-search
This is the beginning of our journey, and while today not all parts of the Android code base are cross-referenced, you can expect to see this grow over time.
We hope this makes it easier to engage with the Android code base!

AOSP Application Updates

Posted by Raman Tenneti, AOSP Software Engineer and Ally Sillins, AOSP Program Manager

When we started the Android Open Source Project (AOSP) 10 years ago, we included some basic applications in the AOSP build for three main purposes:

  1. to provide a usable set of applications for someone building an Android device from our AOSP
  2. to serve as a demonstration for the nascent Android app developer community, showcasing how they should build some of these applications
  3. to, as part of the platform, provide functionality to other Android applications that would interact with them through the standard Android APIs like the common intents

However, as the Android ecosystem has matured over time, we've noticed a healthy growth of alternative applications - both as open source and proprietary implementations - developed by the developer community. These alternative applications are not only capable to serve the first two purposes, but often times showcase richer set of features demonstrating the power of Android. Late last year, we began to clean up these applications in AOSP to focus more effectively on the last purpose — their role to provide functionality to other Android applications as part of the platform.

To date, the following 3 apps have been cleaned up: Music, Calendar, and Calculator. See below for details on these updates. Going forward, you can expect to see similar efforts with the other applications in the AOSP repository.

As always, we're excited to hear your feedback on the developer website or through our AOSP forum.

Music Application

AOSP's Music app can now playback music, one file at a time, and exposes itself as an intent handler for the android.media.browse.MediaBrowserService. The app has controls to play and pause, and a slider moving forward and backward. Features removed include: Music Icon, Artists, Albums, Songs, Playlists, Search, and Settings.

Calendar Application

AOSP's Calendar app now exposes itself as an intent handler for the calendar events. New events cannot be created and existing events cannot be edited or deleted. The following features have been deleted: support for multiple accounts, reminders and settings. In addition, some features remain that are not needed for providing a part of the platform functionality: views for day, week, and month. This app may be further simplified in the future.

Calculator App

The calculator application is a standalone app, and does not function as part of the platform and hence has been removed from the AOSP build. However, the application will continue to exist as an open source project separately.

More visibility into the Android Open Source Project

Posted by Jeff Bailey, AOSP Team

AOSP has been around for more than 10 years and visibility into the project has often been restricted to the Android Team and Partners. A lot of that has been rooted in business needs: we want to have fun things to show off at launches and the code wasn't factored in a way that let us do more in the open.

At the Android Developer Summit last month, we demoed GSI running on a number of partner devices, enabled through Project Treble. The work done to make that happen has provided the separation needed, and has also made it easier to work with our partners to upstream fixes for Android into AOSP. As a result of this, more than 40% of the commits to our git repository came in through our open source tree in Q3 of this year.

Publishing Android's Continuous Integration Dashboard

In order to support the developers working directly in AOSP and our partners upstreaming changes, we have enabled more than 8000 tests in presubmit -- tests that are run before the code is checked in -- and are working to add other continuous testing like the Compatibility Test Suite which ensures that our AOSP trees are in a continuously releasable state. Today we are excited to open this up for you through https://ci.android.com/.

On this dashboard, across the top are the targets that we are building, down the left are the revisions. As we add more targets (such as GSI), they will appear here. Each square in the table provides access to the build artifacts. An anchor on the left provides a permanent URL for that revision. Find out more at https://source.android.com/setup/build/dashboard.

Our DroidCop team (similar to Chromium's Tree Sherrifs) watches this dashboard and works with developers to ensure the health of the tree. This is just the start for us and we are building on this tool to add more in the coming months.

I'd like to thank the Android Engineering Productivity Team for embracing this and I'm excited for us to take this step! I'd love to hear how you use this. Contact me at @jeffbaileyaosp on Twitter, [email protected], or tag /u/jeffbailey in a post to reddit.com/r/androiddev.

AndroidX Development is Now Even Better

Posted by Aurimas Liutikas, software engineer on AndroidX team

AndroidX (previously known as Android Support Library) started out as a small set of libraries intended to provide backwards compatibility for new Android platform APIs and, as such, its development was strictly tied to the platform. As a result, all work was done in internal Google branches and then pushed to the public Android Open Source Project (AOSP) together with the platform push. With this flow, external contributions were limited to a narrow window of time where the internal and AOSP branches were close in content. On top of that, it was difficult to contribute -- in order to do a full AndroidX build and testing, external developers had to check out >40GB of the full Android platform code.

Today, the scope of AndroidX has expanded dramatically and includes libraries such as AppCompat for easier UI development, Room for database management, and WorkManager for background work. Many of these libraries implement higher-level abstractions and are less tied to new revisions of the Android platform, and all libraries are designed with backwards compatibility in mind from the start. Several libraries, such as RecyclerView and Fragment, are purely AndroidX-side implementations with few ties to the platform.

Starting a little over two years ago, we began a process of unbundling -- moving AndroidX out of Android platform builds into its own separate build. We had to do a great deal of work, including migrating our builds from make to Gradle as well as migrating all of our API tracking tools and documentation generation out of the platform build. With that process completed, we reached a point where a developer can now check out a minimal AndroidX project, open it in Android Studio, and build using the public SDK and public Android Gradle Plugin.

The Android developer community has long expressed a desire to contribute more easily to AndroidX; however, this was always a challenge due to the reasons described above. This changes today: AndroidX development is moving to public AOSP. That means that our primary feature development (except for top-secret integrations with the platform ?) and bug fixes will be done in the open using the r.android.com Gerrit review tool and changes will be visible in the aosp/androidx-master-dev branch.

We are making this change to give better transparency to developers; it gives developers a chance to see features and bug fixes implemented in real-time. We are also excited about receiving bug fix contributions from the community. We have written up a short guide on how to go about contributing a patch.

In addition to regular development, AOSP will be a place for experimentation and prototyping. You will see new libraries show up in this repository; some of them may be removed before they ship, change dramatically during pre-alpha development, or merge into existing libraries. The general rule is that only the libraries on maven.google.com are officially ready for external developer usage.

Finally, we are just getting started. We apologize for any rough edges that you might have when contributing to AndroidX, and we request your feedback via the public AndroidX tracker if you hit any issues.