Category Archives: Android Developers Blog

An Open Handset Alliance Project

Optimize for Android (Go edition): Lessons from Google apps Part 3

Posted by Niharika Arora, Developer Relations Engineer

In Part 1 and Part 2 of our “Optimizing for Android Go” blog series, we discussed why we should consider building for Android Go and how to optimize your app to perform well on Go devices. In this blog, we will talk about the tools which helped Google optimize their Google apps performance.

Tools

Monitoring Memory

Analyze Memory Footprint 

 1.    To determine the memory footprint for an application, any of the following metrics may be used:
    • Resident Set Size (RSS): The number of shared and non-shared pages used by the app
    • Proportional Set Size (PSS): The number of non-shared pages used by the app and an even distribution of the shared pages (for example, if three processes are sharing 3MB, each process gets 1MB in PSS)
      • Note: Private Set Size (PSS) = Private memory + (shared memory / the number of processes sharing).
    • Unique Set Size (USS): The number of non-shared pages used by the app (shared pages are not included)

PSS is useful for the operating system when it wants to know how much memory is used by all processes since pages don’t get counted multiple times. PSS takes a long time to calculate because the system needs to determine which pages are shared and by how many processes. RSS doesn't distinguish between shared and non-shared pages (making it faster to calculate) and is better for tracking changes in memory allocation.

So, which method should you choose? The choice depends on the usage of shared memory.

For example, if the shared memory is being used by the application only then we should use the RSS approach. While, if the shared memory is taken by the Google Play Services then we should use the USS approach. For more understanding, please read here

2.    Take a heap dump and analyze how much memory is utilized by the running processes. Follow
    • Review the Prerequisites. 
      • Developer options Don't keep activities must be OFF. 
      • Use recent release builds for testing.
    • Execute the user journey you desire to measure.
    • Run the following command:
                    adb shell am dumpheap <You Android App Process ID> <output-file-name>
    • In a second terminal, run the following command and wait for message indicating that the “heap dump has completed”:
adb logcat | grep hprof
    • Run:
adb pull <output-file-name> 
 
This will pull the generated file to your machine for analysis.
 
To get info on native heap, read here :

To know about Java heap, read here :

3.    Understand low-memory killer

In Android, we have a process called low memory killer, and this will pick a process from the device and will kill that process when the device is under low RAM, the thresholds can be tuned by OEMs. By doing so, you will get back all the memory that the process was using.
But what if the low memory killer kills the process that the user cares about?
 
In Android, we have a priority list of applications and based on that priority list we remove the app when the low memory killer comes into play. Read more here.

You can run this command and know :
adb shell dumpsys activity oom

To check stats on low memory killer :
adb shell dumpsys activity lmk

For more information, please check Perfetto documentation for Memory.
 

Tools 

 1.    Debug Memory usage using Perfetto
This is one the best tools to find where all your app memory is consumed. Use Perfetto to get information about memory management events from the kernel. Deep dive and understand how to profile native and Java heap here
 
2.    Inspect your memory usage using Memory Profiler
The Memory Profiler is a component in the Android Profiler that helps you identify memory leaks and memory churn that can lead to stutter, freezes, and even app crashes. It shows a real time graph of your app's memory use and lets you capture a heap dump, force garbage collections, and track memory allocations. To learn more about inspecting performance, please check MAD skills videos here
 
3.    Utilize meminfo
You may want to observe how your app's memory is divided between different types of RAM allocation with the following adb command: 

adb shell dumpsys meminfo <package_name|pid> [-d]


You can view the following seven memory categories with Meminfo:
    • Java heap – memory allocated by Java code
    • Native heap – memory allocated by native code. These are best understood using debug malloc. Allocations made by the application from C or C++ code using malloc or new.
    • Code – memory used for Java, native code and some resources, including dex bytecode, shared libraries and fonts
    • Stack – memory used for both native and Java stacks. This usually has to do with how many threads your application is running.
    • Graphics – Memory used for graphics buffer queues to display pixels to the screen, GL surfaces and textures and such.
    • Private Other – uncategorized private memory
    • System – memory shared with the system or otherwise under the control of the system.

Key memory terms:

    • Private – Memory used only by the process.
    • Shared – System memory shared with other processes.
    • Clean – Memory-mapped pages that can be reclaimed when under memory pressure.
    • Dirty – Memory-mapped page modified by a process. These pages may be written to file/swap and then reclaimed when under memory pressure.

Note :

    • Debug class is super useful and provides different methods for Android applications, including tracing and allocation counts. You can read about usage here.
    • For deeper understanding and tracking allocations for each page, read about page owner here.
4.    Detailed analysis using showmap
The showmap command provides a much more detailed breakdown of memory than friendly meminfo. It lists the name and sizes of memory maps used by a process. This is a summary of the information available at /proc/<pid>/smaps, which is the primary source of information used in dumpsys meminfo, except for some graphics memory.
$adb root
$ adb shell pgrep <process>
Output - process id
$ adb shell showmap <process id>

Sample Output :

 virtual                     shared   shared  private  private

    size      RSS      PSS    clean    dirty    clean    dirty object

-------- -------- -------- -------- -------- -------- -------- ------------------------------

    3048      948      516      864        0       84        0 /data/app/……

    2484     2088     2088        0        0     2084        4 /data/app/……..

     144       72        2       68        4        0        0 /data/dalvik-cache/arm64/system@framework@<...>.art

     216      180        5      176        4        0        0 /data/dalvik-cache/arm64/system@framework@<...>.art

     168      164        8      136       24        0        4 /data/dalvik-cache/arm64/system@framework@<...>.art

      12        8        0        4        4        0        0 /data/dalvik-cache/arm64/system@framework@<...>.art

    1380     1300       73     1100      164        0       36 /data/dalvik-cache/arm64/system@framework@<...>.art

Common memory mappings are:

    • [anon:libc_malloc] - Allocations made from C/C++ code using malloc or new.
    • *boot*.art - The boot image. A Java heap that is pre-initialized by loading and running static initializers where possible for common frameworks classes.
    • /dev/ashmem/dalvik-main space N - The main Java heap.
    • /dev/ashmem/dalvik-zygote space - The main Java heap of the zygote before forking a child process. Also known as the zygote heap.
    • /dev/ashmem/dalvik-[free list ] large object space - Heap used for Java objects larger than ~12KB. This tends to be filled with bitmap pixel data and other large primitive arrays.
    • *.so - Executable code from shared native libraries loaded into memory.
    • *.{oat,dex,odex,vdex} - Compiled dex bytecode, including optimized dex bytecode and metadata, native machine code, or a mix of both.
5.    Analyze native memory allocations using malloc debug
Malloc debug is a method of debugging native memory problems. It can help detect memory corruption, memory leaks, and use after free issues. You can check this documentation for more understanding and usage.  
 
6.    Use Address Sanitizer to detect memory errors in C/C++ code
Beginning with Android 27, Android NDK supports Address Sanitizer which is a fast compiler-based tool for detecting memory bugs in native code. ASan detects:
      • Stack and heap buffer overflow/underflow
      • Heap use after free
      • Stack use outside scope
      • Double free/wild free

            ASan runs on both 32-bit and 64-bit ARM, plus x86 and x86-64. ASan's CPU overhead is roughly 2x, code size overhead is between 50% and 2x, and the memory overhead is large (dependent on your allocation patterns, but on the order of 2x). To learn more, read here.

            Camera from the Google team used it and automated the process that would run and get back to them in the form of alerts in case of Asan issues, and found it really convenient to fix memory issues missed during code authoring/review.

            Monitoring Startup

            Analyze Startup

            1.    Measure and analyze time spent in major operations
            Once you have a complete app startup trace, look at the trace and measure time taken for major operations like bindApplication, activitystart etc.

            Look at overall time spent to

              • Identify which operations occupy large time frames and can be optimized
              • Identify which operations consume high time where it is not expected.
              • Identify which operations cause the main thread to be blocked
            2.    Analyze and identify different time consuming operations and their possible solutions
              • Identify all time consuming operations.
              • Identify any operations which are not supposed to be executed during startup (Ideally there are a lot of legacy code operations which we are not aware about and not easily visible when looking at our app code for performance)
              • Identify which all operations are absolutely needed OR could be delayed until your first frame is drawn.
            3.    Check Home activity load time
            This is your app’s home page and often performance will depend on the loading of this page. For most apps, there is a lot of data displayed on this page, spanning multiple layouts and processes running in background. Check the home activity layout and specifically look at the Choreographer.onDraw method of the home activity.
              • Measure time taken for overall operations of measure, draw,inflate,animate etc.
              • Look at frame drops.
              • Identify layouts taking high time to render or measure.
              • Identify assets taking a long time to load.
              • Identify layouts not needed but still getting inflated.

            Tools 

             1.    Perfetto
              • To know CPU usage, thread activity, frame rendering time, Perfetto will be the best tool.
              • Record trace either by using command line or UI tools like Perfetto. Add app package name with the -a tag, to filter data for your app. Some ways to capture trace :
              • Produces a report combining data from the Android kernel, such as the CPU scheduler, disk activity, and app threads.
              • Best when enabled with custom tracing to know which method or part of code is taking how long and then develop can dig deep accordingly.
              • Understand Atrace, and ftrace while analyzing traces through Perfetto.
            2.    App Startup library
            The App Startup library provides a straightforward, performant way to initialize components at application startup. Both library developers and app developers can use App Startup to streamline startup sequences and explicitly set the order of initialization. Instead of defining separate content providers for each component you need to initialize, App Startup allows you to define component initializers that share a single content provider. This can significantly improve app startup time. To find how to use it in your app, refer here
             
            3.    Baseline Profiles
            Baseline Profiles are a list of classes and methods included in an APK used by Android Runtime (ART) during installation to pre-compile critical paths to machine code. This is a form of profile guided optimization (PGO) that lets apps optimize startup, reduce jank, and improve performance for end users. Profile rules are compiled into a binary form in the APK, in assets/dexopt/baseline.prof.

            During installation, ART performs Ahead-of-time (AOT) compilation of methods in the profile, resulting in those methods executing faster. If the profile contains methods used in app launch or during frame rendering, the user experiences faster launch times and/or reduced jank. For more information on usage and advantages, refer here.  

            4.    Android CPU Profiler
            You can use the CPU Profiler to inspect your app’s CPU usage and thread activity in real time while interacting with your app, or you can inspect the details in recorded method traces, function traces, and system traces. The detailed information that the CPU Profiler records and shows is determined by which recording configuration you choose:
              • System Trace: Captures fine-grained details that allow you to inspect how your app interacts with system resources.
              • Method and function traces: For each thread in your app process, you can find out which methods (Java) or functions (C/C++) are executed over a period, and the CPU resources each method or function consumes during its execution.
            5.    Debug API + CPU Profiler
            To give apps the ability to start and stop recording CPU profiling and then inspect in CPU profiler is what Debug API is all about. It provides information about tracing and allocation counts the same way using startMethodTracing() and stopMethodTracing().
             

            Debug.startMethodTracing("sample") - Starts recording a trace log with the name you provide


             Debug.stopMethodTracing() - he system begins buffering the generated trace data, until the

             application calls this method.

            Usage

              • Debug API is designed for short intervals or scenarios that are hard to start/stop recording manually. (Used it once to find the lock contention happening due to some library)
              • To generate a method trace of an app's execution, we can instrument the app using the Debug class. This way developers get more control over exactly when the device starts and stops recording tracing information.
            6.    MacroBenchmark
              • Measures Scrolling / Animation rendering time.
              • Use a UiAutomator to trigger a scroll or animation. (It captures frame timing / janks for whatever the app is doing. Scroll and animations are just the easiest ways to produce frames where jank is noticeable)
              • Requires Android 10 or higher to run the tests.
              • Can view traces on Systrace/Perfetto Traces.
              • FrameTimingMetric is the API reporting frame time in ms.
            This sample can be used for app instrumentation. 
             

              • Added in API level 30 and supported in the latest Studio Bumblebee preview (2021.1)
              • Uses simpleperf with customized build scripts for profiling.
              • Simpleperf supports profiling java code on Android >M.
              • Profiling a release build requires one of following:
                • Device to be rooted
                • Android >=O, use a script wrap.sh and make android::debuggable=“true” to enable profiling.
                • Android >=Q, add profileable in manifest flag.

            <profileable android:shell=["true" | "false"] android:enable=["true" | "false"] />

              • Helpful in app instrumentation with Macrobenchmark.
            8.    MicroBenchmark
            The Jetpack Microbenchmark library allows you to quickly benchmark your Android native code (Kotlin or Java) from within Android Studio. The library handles warmup, measures your code performance and allocation counts, and outputs benchmarking results to both the Android Studio console and a JSON file with more detail. Read more here.

            Monitoring App size

            No user wants to download a large APK that might consume most of their Network/Wifi Bandwidth, also most importantly, space inside the mobile device.

            The size of your APK has an impact on how fast your app loads, how much memory it uses, and how much power it consumes. Reducing your app's download size enables more users to download your app.


            Tools

            • Use the Android Size Analyzer
            The Android Size Analyzer tool is an easy way to identify and implement many strategies for reducing the size of your app. It is available as both an Android Studio plugin as well as a standalone JAR
            • Remove unused resources using Lint
            The lint tool, a static code analyzer included in Android Studio, detects resources in your res/ folder that your code doesn't reference. When the lint tool discovers a potentially unused resource in your project, it prints a message like the following example.

            Note : Libraries that you add to your code may include unused resources. Gradle can automatically remove resources on your behalf if you enable shrinkResources in your app's build.gradle file.

            • Native animated image decoding
            In Android 12 (API level 31), the NDK ImageDecoder API has been expanded to decode all frames and timing data from images that use the animated GIF and animated WebP file formats. When it was introduced in Android 11, this API decoded only the first image from animations in these formats. 
             
            Use ImageDecoder instead of third-party libraries to further decrease APK size and benefit from future updates related to security and performance. 
             
            For more details on the API, refer to the API reference and the sample on GitHub.
            • Crunch PNG files using aapt
            The aapt tool can optimize the image resources placed in res/drawable/ with lossless compression during the build process. For example, the aapt tool can convert a true-color PNG that does not require more than 256 colors to an 8-bit PNG with a color palette. Doing so results in an image of equal quality but a smaller memory footprint. Read more here.

            Note : Please check Android developer documentation for all the useful tools which can help you identify and help fix such performance issues.

            Recap

            This part of the blog captures the tools used by Google to identify and fix performance issues in their apps. They saw great improvements in their metrics. Most Android Go apps could benefit from applying the strategies described above. Optimize and make your app delightful and fast for your users!

            Better Device Compatibility with CameraX

            Posted by The Android Team CameraX is an Android Jetpack library that makes it easy to incorporate camera functionality directly in your Android app. That’s why we focus heavily on device compatibility out-of-the-box, so you can focus on what makes your app unique.

            In this post, we’ll look at three ways CameraX makes developers’ lives easier when it comes to device compatibility. First, we’ll take a peek into our CameraX Test Lab where we test over 150 physical phones every day. Second, we’ll look at Quirks, the mechanism CameraX uses to automatically handle device inconsistencies. Third, we’ll discuss the ways CameraX makes it easier to develop apps for foldable phones.


            CameraX Test Lab

            A single rack in our CameraX Test Lab on the left, and on the right, a moving image of the inside of a test inclusure with rotating phone mount 
            (Left) A single rack in our CameraX Test Lab. Each test enclosure contains two identical Android phones for testing front and back cameras. (Right) A GIF showing the inside of a test inclosure, with a rotating phone mount (for testing portrait and landscape orientations) and a high-resolution test chart (not pictured).

            We built the CameraX Test Lab to ensure CameraX works on the Android devices most people have in their pockets. The Test Lab opened in 2019 with 52 phone models. Today, the Test Lab has 150 phone models. We prioritize devices with the most daily active users over the past 28 days (28DAUs) and devices that leverage a diverse range of systems on a chip (SoCs). The Test Lab currently covers over 750 million 28DAUs. We also test many different Android versions, going back to Android 5.1 (Lollipop).

            To generate reliable test results, each phone model has its own test enclosure to control for light and other environmental factors. Each enclosure contains two phones of the same model to simplify testing the front and back cameras. On the opposite side of the test enclosure from the phones, there’s a high-resolution test chart. This chart has many industry-standard tests for camera attributes like color correctness, resolution, sharpness, and dynamic range. The chart also has some specific elements for functional tests like face detection.

            When you adopt CameraX in your app, you get the assurance of this continuous testing across many devices and API levels. Additionally, we’re continuously making improvements to the Test Lab, including adding new phones based on market trends to ensure that the majority of your users are well represented. See our current test device list for the latest inventory in our Test Lab.

            Quirks

            Google provides a Camera Image Test Suite so that OEM’s cameras meet a baseline of consistency. Still, when dealing with the wide range of devices that run Android, there can be differences in the end user camera experience. CameraX includes an abstraction layer, called Quirks, to remove these variations in behavior so that CameraX behaves consistently across all devices with no effort from app developers.

            We find these quirks based on our own manual testing, the Test Lab’s automatic testing, and bug reports filed in our public CameraX issue tracker. As of today, CameraX has over 30 Quirks that automatically fix behavior inconsistencies for developers. Here are a few examples:

            • OnePixelShiftQuirk: Some phones shift a column of pixels when converting YUV data to RGB. CameraX automatically corrects for this on those devices.
            • ExtensionDisableQuirk: For phones that don’t support extensions or have broken behavior with extensions, CameraX disables certain extensions.
            • CameraUseInconsistentTimebaseQuirk: Some phones do not properly timestamp video and audio. CameraX fixes the timestamps so that the video and audio align properly.

            These are just a few examples of how CameraX automatically handles quirky device behavior. We will continue to add more corrections as we find them, so app developers won’t have to deal with these one-offs on their own. If you find inconsistent behavior on a device you’re testing, you can file an issue in the CameraX component detailing the behavior and the device it’s happening on.

            Foldable phones

            Foldables continue to be the fastest growing smartphone form factor. Their flexibility in screen size adds complexity to camera development. Here are a few ways that CameraX simplifies the development of camera apps on foldables.

            CameraX’s Preview use case handles differences between the aspect ratio of the camera and the aspect ratio of the screen. With traditional phone and tablet form factors, this difference should be small because Section 7.5.5 of the Android Compatibility Definition Document requires that the “long dimension of the camera aligns with the screen’s long dimension.” However, with foldable devices the screen aspect ratio can change, so this relationship might not always hold. With CameraX you can always preserve aspect ratio by filling the PreviewView (which may crop the preview image) or fitting the image into the PreviewView (which may result in letterboxing or pillarboxing). Set PreviewView.ScaleType to specify which method to use.

            The increase in foldable devices also increases the possibility that your app may be used in a multi-window environment. CameraX is set up for multi-window support out-of-the-box. CameraX handles all aspects of lifecycle management for you, including the multi-window case where other apps can take priority access of singleton resources, such as the microphone or camera. This means no additional effort is required from app developers when using CameraX in a multi-window environment.

            We’re always looking for more ways to improve CameraX to make it even easier to use. With respect to foldables, for example, we’re exploring ways to let developers call setTargetResolution() without having to take into account the different configurations a foldable device can be in. Keep an eye on this blog and our CameraX release notes for updates on new features!

            Getting started with CameraX

            We have a number of resources to help you get started with CameraX. The best starting place is our CameraX codelab. If you want to dig a bit deeper with CameraX, check out our camera code samples, ranging from a basic app to more advanced features like camera extensions. For an overview of everything CameraX has to offer, see our CameraX documentation. If you have any questions, feel free to reach out to us on our CameraX discussion group.

            5 Play Console updates to help you understand your app’s delivery performance

            Posted by Lidia Gaymond, Product Manager, Google PlayPowered by Android App Bundles, Google Play gives all developers the benefits of modern Android distribution. As the Android ecosystem expands, it’s more important than ever to know how your app is being delivered to different devices.

            Delivery insights help you better understand and analyze your app’s delivery performance and what contributes to it, and take action to optimize the experience for your users. Here are five recent Play Console updates you can use to get more insight into your delivery performance.


            1. When you release your app, you’ll now see its expected app size and update size at the point of release creation, so you can determine if the size change from the previous release is acceptable.

            Screenshot of Google Play Console showing expected app size and update size
            Get the expected app size and update size when you create a new release.

            2. If you use advanced Play delivery tools, such as Play Asset Delivery or Play Feature Delivery, detailed information about how these are shipped to users are now available on the Statistics page and in the Delivery tab in App bundle explorer. Understanding your feature modules and asset packs usage can help you make better decisions about further modularization and uncover usage patterns across your users.

            Screenshot of the Devliery tab in the App bundle explorer page in Play Console
            Get detailed information about how your feature modules are shipped to users in the Delivery tab in the App bundle explorer page in Play Console.

            Screenshot of performance metrics on the Statistics page in Play Console
            See per module performance metrics on the Statistics page in Play Console.


            3. When analyzing your existing release, you can now see how many users are on it to help you assess the “freshness” of your install base and how quickly users migrate to new releases. To improve your update rate, consider using the In-app updates API.

            Screenshot of the Release Summary showing percentage of install base on this release in Releases Overview in Play Console
            Know how many users are on your existing release and how quickly users migrate to new releases.

            4. For a deeper dive into your individual app version performance, you can find information about your download size per device model, most common update sizes, and install base in App bundle explorer.

            Screenshot of App bundle explorer page in Play Console
            Evaluate device-specific bundle download size and install base on the App bundle explorer page.

            5. All of these features are also available in your App Dashboard, where you can track these measurements over time alongside other app metrics.

            Screenshot of App bundle explorer page in Play Console
            Monitor these new delivery metrics on your App Dashboard.

            We hope these changes will help you make more informed decisions about your app development and provide you with a detailed view of how your app is being delivered to end user devices.


            How useful did you find this blog post?

            Google Play Logo

            Modern Android Development at Android Developer Summit ‘22

            Posted by Nick Butcher, Developer Relations Engineer

            The Android Developer Summit is back and the first stop on the world tour just finished! We focussed on the latest developments in Modern Android Development: our set of libraries, tools and guidance that make it faster and easier to build amazing Android apps. Here a recap of the top 3 announcements from the conference.

            #1: Jetpack Compose October ‘22

            The October ‘22 stable release of Jetpack Compose brings support for staggered grids, snapping behaviors, pull to refresh, drawing text directly to canvas and many bug fixes and performance improvements. It also includes the first stable release of the Compose Material 3 library, helping you to build fresh, beautiful apps with updated components and styling.

            We’ve also released a new Gradle BOM to simplify how you specify compose dependencies and launched the first alphas of Compose for Android TV—in our continued efforts to bring the joys of writing Compose UIs to all Android form factors.

            #2: Stable Baseline Profile generation

            If you haven’t tried them yet, Baseline Profiles are a powerful way to improve app startup and runtime performance—without changing a single line of app code—and we’ve seen them yield up to 40% faster startup times.

            With Jetpack Benchmark 1.1 and Android Gradle Plugin 7.3 both reaching stable, the toolchain for generating a profile is now completely stable and ready to integrate into your app and start seeing the speed benefits. See the “Making Apps Blazing Fast with Baseline Profiles” talk for all the details.

            #3: Architectural Guidance

            A solid app needs a strong architecture and we’ve been bikeshedding on your behalf to provide detailed guidance on building scalable, testable, high quality apps. Check out the talks and new docs on Modularization, State holders & State Production, UI Events, Flow collection, building Offline first apps and more.

            Those were the top three announcements about Modern Android Development at Android Developer Summit. To learn more, check out the full playlist.

            Material Design 3 for Compose hits stable

            Posted by Gurupreet Singh, Developer Advocate; Android

            Today marks the first stable release of Compose Material 3. The library allows you to build Jetpack Compose UIs with Material Design 3, the next evolution of Material Design. You can start using Material Design 3 in your apps today!

            Note: The terms "Material Design 3", "Material 3", and "M3" are used interchangeably. 

            Material 3 includes updated theming and components, exclusive features like dynamic color, and is designed to be aligned with the latest Android visual style and system UI.
            ALT TEXT
            Multiple apps using Material Design 3 theming

            You can start using Material Design 3 in your apps by adding the Compose Material 3 dependency to your build.gradle files:

            // Add dependency in module build.gradle

            implementation "androidx.compose.material3:material3:$material3_version" 


            Note: See the latest M3 versions on the Compose Material 3 releases page.


            Color schemes

            Material 3 brings extensive, finer grained color customisation, and comes with both light and dark color scheme support out of the box. The Material Theme Builder allows you to generate a custom color scheme using core colors, and optionally export Compose theming code. You can read more about color schemes and color roles.
            ALT TEXT
            Material Theme Builder to export Material 3 color schemes


            Dynamic color

            Dynamic color derives from the user’s wallpaper. The colors can be applied to apps and the system UI.

            Dynamic color is available on Android 12 (API level 31) and above. If dynamic color is available, you can set up a dynamic ColorScheme. If not, you should fall back to using a custom light or dark ColorScheme.
            Reply Dynamic theming from wallpaper(Left) and Default app theming (Right)

             

             


















            The ColorScheme class provides builder functions to create both dynamic and custom light and dark color schemes:

            Theme.kt

            // Dynamic color is available on Android 12+
            val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
            val colorScheme = when {
              dynamicColor && darkTheme -> dynamicDarkColorScheme(LocalContext.current)
              dynamicColor && !darkTheme -> dynamicLightColorScheme(LocalContext.current)
              darkTheme -> darkColorScheme(...)
              else -> lightColorScheme(...)
            }

            MaterialTheme(
              colorScheme = colorScheme,
              typography = typography,
              shapes = shapes
            ) {
              // M3 App content
            }


            Material components

            The Compose Material 3 APIs contain a wide range of both new and evolved Material components, with more planned for future versions. Many of the Material components, like CardRadioButton and CheckBox, are no longer considered experimental; their APIs are stable and they can be used without the ExperimentalMaterial3Api annotation.

            The M3 Switch component has a brand new UI refresh with accessibility-compliant minimum touch target size support, color mappings, and optional icon support in the switch thumb. The touch target is bigger, and the thumb size increases on user interaction, providing feedback to the user that the thumb is being interacted with.
            ALT TEXT
            Material 3 Switch thumb interaction

            Switch(
                  checked = isChecked,
                  onCheckedChange = { /*...*/ },
                  thumbContent = {
                      Icon(
                          imageVector = Icons.Default.Check,
                          contentDescription = stringResource(id = R.string.switch_check)
                      )
                  },
              )


            Navigation drawer components now provide wrapper sheets for content to change colors, shapes, and elevation independently.

            Navigation drawer component

            Content
            ModalNavigationDrawerModalDrawerSheet
            PermanentNavigationDrawer

            PermanentDrawerSheet
            DismissableNavigationDrawerDismissableDrawerSheet


            ALT TEXT
            ModalNavigationDrawer with content wrapped in ModalDrawerSheet

            ModalNavigationDrawer {
                ModalDrawerSheet(
                    drawerShape = MaterialTheme.shapes.small,
                    drawerContainerColor = MaterialTheme.colorScheme.primaryContainer,
                    drawerContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                    drawerTonalElevation = 4.dp,
                ) {
                    DESTINATIONS.forEach { destination ->
                        NavigationDrawerItem(
                            selected = selectedDestination == destination.route,
                            onClick = { ... },
                            icon = { ... },
                            label = { ... }
                        )
                    }
                }
            }


            We have a brand new CenterAlignedTopAppBar  in addition to already existing app bars. This can be used for the main root page in an app: you can display the app name or page headline with home and action icons.


            ALT TEXT
            Material CenterAlignedTopAppBar with home and action items.

            CenterAlignedTopAppBar(
                      title = {
                          Text(stringResources(R.string.top_stories))
                      },
                      scrollBehavior = scrollBehavior,
                      navigationIcon =  { /* Navigation Icon */},
                      actions = { /* App bar actions */}
                  )


            See the latest M3 components and layouts on the Compose Material 3 API reference overview. Keep an eye on the releases page for new and updated APIs.


            Typography

            Material 3 simplified the naming and grouping of typography to:
            • Display
            • Headline
            • Title
            • Body
            • Label
            There are large, medium, and small sizes for each, providing a total of 15 text style variations.

            The 
            Typography constructor offers defaults for each style, so you can omit any parameters that you don’t want to customize:

            val typography = Typography(
              titleLarge = TextStyle(
                  fontWeight = FontWeight.SemiBold,
                  fontSize = 22.sp,
                  lineHeight = 28.sp,
                  letterSpacing = 0.sp
              ),
              titleMedium = TextStyle(
                  fontWeight = FontWeight.SemiBold,
                  fontSize = 16.sp,
                  lineHeight = 24.sp,
                  letterSpacing = 0.15.sp
              ),
              ...
            }


            You can customize your typography by changing default values of TextStyle and font-related properties like fontFamily and letterSpacing.

            bodyLarge = TextStyle(
              fontWeight = FontWeight.Normal,
              fontFamily = FontFamily.SansSerif,
              fontStyle = FontStyle.Italic,
              fontSize = 16.sp,
              lineHeight = 24.sp,
              letterSpacing = 0.15.sp,
              baselineShift = BaselineShift.Subscript
            )


            Shapes

            The Material 3 shape scale defines the style of container corners, offering a range of roundedness from square to fully circular.

            There are different sizes of shapes:
            • Extra small
            • Small
            • Medium
            • Large
            • Extra large

            ALT TEXT
            Material Design 3 shapes used in various components as default value.

            Each shape has a default value but you can override it:

            val shapes = Shapes(
              extraSmall = RoundedCornerShape(4.dp),
              small = RoundedCornerShape(8.dp),
              medium = RoundedCornerShape(12.dp),
              large = RoundedCornerShape(16.dp),
              extraLarge = RoundedCornerShape(28.dp)
            )


            You can read more about applying shape.


            Window size classes

            Jetpack Compose and Material 3 provide window size artifacts that can help make your apps adaptive. You can start by adding the Compose Material 3 window size class dependency to your build.gradle files:

            // Add dependency in module build.gradle

            implementation "androidx.compose.material3:material3-window-size-class:$material3_version"


            Window size classes group sizes into standard size buckets, which are breakpoints that are designed to optimize your app for most unique cases.


            ALT TEXT
            WindowWidthSize Class for grouping devices in different size buckets

            See the Reply Compose sample to learn more about adaptive apps and the window size classes implementation.


            Window insets support

            M3 components, like top app bars, navigation drawers, bar, and rail, include built-in support for window insets. These components, when used independently or with Scaffold, will automatically handle insets determined by the status bar, navigation bar, and other parts of the system UI.

            Scaffold now supports the contentWindowInsets parameter which can help to specify insets for the scaffold content.

            Scaffold insets are only taken into consideration when a topBar or bottomBar is not present in Scaffold, as these components handle insets at the component level.

            Scaffold(
                contentWindowInsets = WindowInsets(16.dp)
            ) {
                // Scaffold content
            }



            Resources

            With Compose Material 3 reaching stable, it’s a great time to start learning all about it and get ready to adopt it in your apps. Check out the resources below to get started.

            Android Dev Summit ‘22: What’s new in Jetpack

            Posted by Amanda Alexander, Product Manager

            Android Jetpack is a key component of Modern Android Development. It is a suite of over 100 libraries, tools and guidance to help developers follow best practices, reduce boilerplate code, and write code that works consistently across Android versions and devices. By using Android Jetpack to improve your productivity, you can focus on building unique features for your app. 

            Most apps on Google Play use Jetpack as a key component of their app architecture, in fact over 90% of the top 1000 apps use Android Jetpack.

            At ADS this week we released updates to three major areas of Jetpack:

            1. Architecture Libraries and Guidance
            2. Application Performance
            3. User Interface Libraries and Guidance

            We’ll take a moment to expand on each of these areas and then conclude with some additional updates that we also shipped.

            Let’s go…


            Architecture Libraries and Guidance

            App architecture libraries and components ensure that apps are robust, testable, and maintainable.

            Managing tasks with WorkManager

            The WorkManager library makes it easy to schedule deferrable, asynchronous tasks that must be run reliably for instance uploading backups or analytics. These APIs let you create a task and hand it off to WorkManager to run when the work constraints are met.

            WorkManager 2.8.0-alpha04 has been updated with the ability to update WorkRequests in a non-intrusive way, preserving original enqueue time, chaining and more. It makes changes to Worker’s constraints much easier, e.g. if constraints need to be changed from one version of an application to another or via configuration set by server-side. Previously, it was possible to achieve only by canceling already scheduled workers and rescheduling them again. However, this approach was very disruptive: already running workers could have been canceled, cadence of periodic workers could have been broken, and the whole chains of workers required reconstruction if one of them needed an update. Now using the update method or ExistingPeriodicWorkPolicy.UPDATE developers don’t have to worry about any of these issues. 


            Data Persistence

            Most applications need to persist local state - whether it be caching results, managing local lists of user enter data, or powering data returned in the UI.  Room is the recommended data persistence layer which provides an abstraction layer over SQLite, allowing for increased usability and safety over the platform.

            In Room 2.5.0-alpha03, we added a new shortcut annotation, @Upsert, which attempts to insert an entity when there is no uniqueness conflict or update the entity if there is a conflict. Moreover, all of Room runtime APIs along with androidx.sqlite have been converted to Kotlin, creating a better experience for Kotlin users such as strict nullability and opening the door to support other Kotlin language features. 


            Android 13 Activity APIs, now backward compatible

            The Activity library includes the ComponentActivity class, a base class built on top of the Android framework’s Activity class which provides APIs that enable Jetpack Compose, other Architecture Components, and support for backporting new features introduced in Android 13 with Activity 1.6.1.

            By using ComponentActivity directly, or either of its subclasses of FragmentActivity or AppCompatActivity, you can use a single API to pick images via the Photo Picker when it is available with an automatic fallback to the Storage Access Framework to allow support back to Android 4.4 (API 19).

            You’ll also be set up for the future with support for the Predictive back gesture introduced in Android 13 simply by upgrading to Activity 1.6.1. The Activity APIs provide a single API for custom back navigation that works back to API 14 and is fully compatible with opting in to predictive back gestures.


            Testing Pagination with the Paging Testing library

            The Paging library provides support for loading very large data sets. To get the most of Paging, the integration includes multiple layers of your application - your repository layer, ViewModel layer, and your UI.

            Paged data flows from the PagingSource or RemoteMediator components in the repository layer to the Pager component in the ViewModel layer. Then the Pager component exposes a Flow of PagingData to the PagingDataAdapter in the UI layer.
            To make it easier to test that integration, Paging 3.2.0-alpha03 introduces a new paging-testing artifact with test specific APIs to make it possible to test each layer in isolation. This first release focuses on the repository layer and specifically around testing a custom PagingSource via the new TestPager APIs to ensure you can test your paging sources in different scenarios that are harder to reproduce with integration tests.


            New Architecture Documentation

            Investing in Architecture is important to improve the quality of your app by making it more robust, testable, maintainable, and scalable. That's why our recommendations on Architecture keep growing! In fact, they've grown so much we released a new Architecture recommendations page that consolidates and centralizes important best practices you can find in our docs.

            The team recently released new guidance on modularization. The guide is split into two parts: 

            The UI layer docs got two new pages:

            • The state holders and UI state page explains the different types of state holders you can find in the UI layer and which implementation you should use depending on the type of logic to perform. 
            • The state production page that shows best practices about how to model and expose UI state depending on the sources of state change. 

            Due to popular demand, the UI events page has been updated with examples of Navigation UI events. We also released new Navigation guidance about providing runtime type safety to the Kotlin DSL and Navigation Compose.

            Lastly, if you need to make your app work offline, we got you covered. The build an offline-first app guide helps you design your app to properly handle reads and writes, and deal with sync and conflict resolution in a device with no Internet connectivity.


            New ViewModel Documentation

            This updated guidance is designed to make it easier to understand when ViewModels are the right tool to reach for when building your UI layer.


            Application Performance

            Using performance libraries allows you to build performant apps and identify optimizations to maintain high performance, resulting in better end-user experiences. 


            Improving Start-up Times

            App speed can have a big impact on a user’s experience, particularly when using apps right after installation. To improve that first time experience, we are continuing to enhance Baseline Profiles. Baseline Profiles allow apps and libraries to provide the Android run-time with metadata about code path usage, which it uses to prioritize ahead-of-time compilation. This profile data is aggregated across libraries and lands in an app’s APK as a baseline.prof file, which is then used at install time to partially pre-compile the app and its statically-linked library code. This can make your apps load faster and reduce dropped frames the first time a user interacts with an app. 

            With AGP 7.3, baseline profile tooling is fully stable, so you don't need alpha dependencies to get a 30%+ performance boost to your app's initial launch and scroll after each app update. 

            In profileinstaller:1.3.0-alpha01, ProfileVerifier allows you to inspect profile compilation in the field, and starting in Android Studio Flamingo Canary 6, the Studio APK Inspector now shows the contents of your APK's baseline profiles.


            Accurate reporting of startup metrics

            Startup metrics are an important part of measuring your app’s performance, but the system (and the Benchmark libraries!) need a signal that marks the completion of the startup phase. That signal is the Activity’s call to reportFullyDrawn()Activity 1.7.0-alpha01 added new APIs in the form of the FullyDrawnReporter APIs that allows multiple components to report when they are ready for interaction. ComponentActivity will wait for all components to complete before calling reportFullyDrawn() on your behalf.

            These APIs are encouraged to enable:

            • Signaling the Android Runtime when startup completes, to ensure all of the code run during a multi-frame startup sequence is included and prioritized for background compilation.
            • Signaling Macrobenchmark and Play Vitals when your application should be considered fully drawn for startup metrics, so you can track performance.

            Two Activity Compose APIs, ReportDrawnWhen and ReportDrawnAfter, have been added to make it more convenient to use the FullyDrawnReporter from individual composables.


            Recomposition Tracing

            We recently launched the first alpha of Jetpack Compose Composition Tracing, a tool that allows you to see composable functions in the Android Studio system trace profiler. This feature combines the benefits of low intrusiveness from system tracing with method tracing levels of detail in your compositions. By adding a dependency on Compose Runtime Tracing, you will be able to see traces of your recomposition call stack in Android Studio Flamingo Canary 5 system traces and click on them to navigate straight to the code! You can read more about the feature and how to set it up in your project here.
            UI screenshot of composables in the system trace
            Composables in the system trace

            User Interface Libraries and Guidance


            Jetpack Compose

            Jetpack Compose, Android’s modern toolkit for building native UI, has launched the Compose October ‘22 release which includes many performance improvements and adds support for staggered grids, drawing text directly to canvas, and pull to refresh. We also published our first Bill of Materials (BOM) to simplify the process of adding Compose library versions to your Gradle dependencies. Check out the What’s New in Jetpack Compose blog post to learn more.


            Wear Tiles Material Library

            Tiles for Wear OS give users glanceable access to information and actions. To help you create tiles, we launched the Tiles Material library, which includes built-in support for Material Design for Wear OS.

            The included components are:

            • Button - a clickable, circular-shaped object, with either icon, text or image with 3 predefined sizes.
            • Chip - a clickable, stadium-shaped object that can contain an icon, primary and secondary labels, and has fixed height and customizable width.
            • CompactChipTitleChip - two variations of the standard Chip that have smaller and larger heights, respectively, and can contain one line of text.
            • CircularProgressIndicator - a colored arc around the edge of the screen with the given start and end angles, which can describe a full or partial circle with the full progress arc behind it.
            • Text - a text element which uses the recommended Wear Material typography styles.

            common tile components. a round icon with a pencil labelled 'button'. a full width rectangle with rounded corners and text labelled 'chip'. similar components, one larger and one smaller, labelled 'title chip' and 'compact chip' respectively. a circle path filled 75% clockwise labelled 'circular progress indicator' and finally text labelled 'text with recommended typography pre-set'

            In addition to components, there are several recommended tile layouts within Material guidelines. Read more about Wear OS Tiles Material Library in this blog.

             

            Add Splash Screen to more devices

            The core SplashScreen library brings the new Android 12 splash screen to all devices from API 23. Using the splash screen library, your application doesn't need any custom SplashScreen Activity and leverages the right APIs for a fast launch of your application. To use it, simply follow the steps outlined in our guide. For more information about the Android 12 splash screen, visit the official documentation.

             

            Other key updates


            Camera 

            The CameraX library makes it easier to add camera capabilities to your app. In 1.2.0-beta01, a new library camera-mlkit-vision was added. It enables an easy integration of CameraX with many MLKit features, including barcode scanning, face detection, text detection, etc. You can find the sample code here. We also added a new experimental Zero-Shutter Lag API which optimizes capture pipeline to have better latency while keeping good image quality. 


            Annotation

            The Annotation library exposes metadata that helps tools and other developers understand your app's code. It provides familiar annotations like @NonNull that pair with lint checks to improve the correctness and usability of your code.

            Annotation 1.5 stable release has been fully migrated to Kotlin sources, resulting in support for Kotlin-specific target use sites and other Kotlin-compatible annotation features.


            Kotlin Multiplatform

            We have been experimenting with Kotlin Multiplatform Mobile from Jetbrains to enable code sharing across platforms. We have experimental previews of the Collections and DataStore libraries for apps targeting Android and iOS and we would like your feedback! Read more here



            This was a brief tour of all the key changes in Jetpack over the past few months. For more details on each Jetpack library, check out the AndroidX release notes, quickly find relevant libraries with the API picker and watch the Google ADS talks for additional highlights.

            What’s new from Android, at Android Dev Summit ‘22

            Posted by Matthew McCullough, Vice President, Product Management, Android Developer

            Just now, we kicked off the first day of Android Dev Summit in the Bay Area, where my team and I covered a number of ways we’re helping you build excellent experiences for users by leveraging Modern Android Development, which can help you extend those apps across the many devices Android has to offer - across all screen sizes from the one on your wrist, to large screens like a tablet or foldables.

            Here’s a recap of what we covered, and don’t forget to watch the full keynote!

            Modern Android Development: Compose October ‘22

            A few years ago, we introduced a set of libraries, tools, services, and guidance we call Modern Android Development, or MAD. From Android Studio, Kotlin, Jetpack libraries and powerful Google & Play Services, our goal is to make it faster and easier for you to build high quality apps across all Android devices.

            For building rich, beautiful UIs, we introduced Jetpack Compose several years ago - this is our recommended UI framework for new Android applications.

            We’re introducing a Gradle Bill of Materials (BOM) specifying the stable version of each Compose library. The first BOM release, Compose October 22, contains Material Design 3 components, lazy staggered grids, variable fonts, pull to refresh, snapping in lazy lists, draw text in canvas, URL annotations in text, hyphenation, and LookAheadLayout. The team at Lyft has benefited from using Compose. They shared “Over 90% of all new feature code is now developed in Compose.”

            We want Compose to help you take advantage of the entire Android ecosystem of devices, Compose for Wear OS hit its 1.0 stable release several weeks ago making it the recommended way to build UI for Wear. Today we announced that we’re growing the offering with the first alpha release of Compose for Android TV. Components like featured carousel and immersive list are already available, with more components coming soon. So if you're learning Android or starting a new app, Jetpack Compose is ready for you!

            Modern Android Development comes to life in Android Studio, our official IDE that provides powerful tools for building apps on every type of Android device. Today, we’re releasing a number of new features for you to test out, including updated templates that are Compose by default and feature Material 3, Live Edit on by default for Compose, Composition Tracing, Android SDK Upgrade Assistant, App Quality Insights Improvements and more. Download the latest preview version of Android Studio Flamingo to try out all the features and to give us feedback.


            Moving image of Android  and Jetpack updates with customer feedback

            Wear OS: the time is now!

            A key device that users are turning to is the smallest and most personal — the watch. We launched our joint platform – Wear OS – with Samsung just last year, and this year, we have seen 3X as many device activations, with amazing new devices hitting the market, like Samsung Galaxy Watch 5 and Google Pixel Watch. Compose for Wear OS, which makes it faster and easier to build Apps for Wear OS, went to 1.0 this summer, and is our recommended approach for building user interfaces for Wear OS apps. More than 20 UI components specifically designed for Wearables, with built-in material theming and accessibility.

            Today, we’re sharing updated templates for Wear OS in Android Studio, as well as a stable Android R emulator system image for WearOS.

            With personalized data from a wearable, it’s important to keep the data completely private and safe, which is why we’ve been working on a solution to make this easier – Health Connect. It’s an API that we built in close collaboration with Samsung for storing and sharing health data - all with a single place for users to easily manage permissions.

            Developers who invest in Wear OS are seeing big results: Todoist increased their install growth rate by 50% since rebuilding their app for Wear 3, and Outdooractive reduced development time by 30% using Compose for Wear OS. Now is the time to bring a unique, engaging experience to your users on Wear OS!



            Making your app work great on tablets & large screens

            As you heard earlier this year: Google is all in on tablets, foldables, and ChromeOS. With amazing new hardware–like Samsung Galaxy Z Fold4, Lenovo P12 Tab Pro, and Google’s upcoming Pixel Tablet, there has never been a better time to review your apps and get them ready for large screens. We’ve been hard at work, with updates to Android, improved Google apps and exciting changes to the Play store making optimized Tablet apps more discoverable.

            We’ve made it easier than ever to test your app on the large screen in Android Studio Electric Eel, including resizable and desktops emulators and visual linting to help you adhere to best practices on any sized screen.

            We’ve also heard that we can help you by providing more design and layout guidance for these devices. To help today, we added new layout guidance for apps by vertical to developer.android.com, as well as developer guidance for Canonical layouts with samples.

            Apps that invest in large screen features are seeing that work pay off when it comes to engagement; take Concepts, which enables amazing stylus interactions like drawing and shape guides for ChromeOS and stylus devices, and saw a 70% higher usage for tablets compared to phones!

            Be on the lookout for more updates on our improvements to Android Studio, Window Manager Jetpack, and more with the Form Factors track, broadcast live on November 9.



            Making it easier to take advantage of platform features in Android 13

            At the heart of a successful platform is the operating system, and Android 13, released in August, brings developer enhancements too many facets of the platform, including personalization, privacy, security, connectivity, and media.

            For example per-app language preferences, improve the experience for multilingual users, allowing people to experience their device in different languages in different contexts.

            The new Photo picker is a permission free way to allow the user to browse and select photos and videos they explicitly want to share with your app, a great example of how Android is focused on privacy.

            To help you target new API levels, we're introducing the Android SDK Upgrade Assistant tool within the latest preview of Android Studio Flamingo, which gives you step-by-step documentation for the most important changes to look for when updating the target SDK of your app.

            These are just a few examples of how we're making it easier than ever to adapt your app to platform changes, while enabling you to take advantage of the latest features Android has to offer.

            Connecting with you around the world at Android Dev Summit

            This is just the first day of Android Dev Summit - where we kicked off with the keynote and dove into our first track on Modern Android Development, we’ve still got a lot more over the coming weeks. Tune in on November 9, when we livestream our next track: Form Factors. Our final technical track will be Platform, livestreamed on November 14.

            If you’ve got a burning question, tweet us using #AskAndroid; we’ll be wrapping up each track livestream with a live Q&A from the team, so you can tune in and hear your question answered live.
            Modern Android Development Track @ Android Dev Summit October 24, 2022 at 9:00 AM PT 
Agenda 9:00 AM Keynote, 9:50 AM Custom Layouts and Graphics in Compose, 10:10 AM Making Apps Blazing Fast with Baseline Profiles, 10:30 State of the Art of Compose Tooling, 10:50 State Holders and State Production in the UI Layer, 11:10 AM 5 ways Compose Improves UI Testing, 11:15 AM 5 Android Studio Features You Don't Want to Miss, 11:30 AM Pre-recorded MAD Technical Talks, 12:20 PM Where to Hoist that State in Compose, 12:25 PM Material You in Compose Apps, 12:30 PM PM Compose Modifiers Deep Dive, 12:50 Practical Room Migrations, 12:55 PM Type Safe, Multi-Module Best Practices with Navigation, 1:00 PM What's New in Android Build, 1:20 PM From Views to Compose: Where Can I Start?, 1:25 PM Test at Scale with Gradle Managed Devices, 1:35 PM MAD #AskAndroid. Broadcast live on d.android.com/dev-summit & YouTube.
            Form Factors Track @ Android Dev Summit November 9, 2022 
Sessions: Deep Dive into Wear OS App Architecture, Build Better Uls Across Form Factors with Android Studio, Designing for Large Screens: Canonical Layouts and Visual Hierarchy Compose: Implementing Responsive UI for Large Screens, Creating Helpful Fitness Experiences with Health Services and Health Connect, The Key to Keyboard and Mouse Support across Tablets and ChromeOS Your Camera App on Different Form Factors,  Building Media Apps on Wear OS,  Why and How to Optimize Your App for ChromeOS. 
Broadcast live on d.android.com/dev-summit & YouTube.
            Platform Track @ Android Dev Summit November 14, 2022 
Sessions: Migrate Your Apps to Android 13,  Presenting a High-quality Media Experience for all Users, Improving Your Social Experience Quality with Android Camera, Building for a Multilingual World Everything About Storage on Android, Migrate to Play Billing Library 5: More flexible subscriptions on Google Play, Designing a High Quality App with the Latest Android Features, Hardware Acceleration for ML on-device, Demystifying Attestation, Building Accessibility Support for Compose. 
Broadcast live on d.android.com/dev-summit & YouTube.

            This year, we’re also really excited to get the opportunity to meet with developers around the world in person, including today in the Bay Area. On November 9, Android Dev Summit moves to London. And the fun will continue in Asia in December with more roadshow stops: in Tokyo on December 16 (more details to come) at Android Dev Summit with Google DevFest, and in Bangalore in mid-December (you can express interest to join here).

            Whether you’re tuning in online, or joining us in-person around the world, it’s feedback from developers like you that help us make Android a better platform. We thank you for the opportunity to work together with you, building excellent apps and delighting users across all of the different devices Android has to offer - enjoy your 2022 Android Dev Summit!

            What’s new in Jetpack Compose

            Posted by Jolanda Verhoef, Android Developer Relations Engineer

            We launched Jetpack Compose over a year ago, and have been busy improving it ever since. We’ve added new features and invented powerful tools to make your experience developing Android UI as productive, intuitive and fun as possible. So, if you're starting a new app, it's time to write it with Compose! With Material Design 3 support, new Bill Of Materials, Compose WearOS Stable and Android TV (alpha), Compose Camp, and many other pieces of news… It's an exciting release!

            Compose in the Community

            In the last year, we’ve seen many companies developing with Compose at scale, implementing new features and migrating screens from views to Compose. For example, we talked to the engineers at Lyft, who told us that over 90% of their new feature code is written in Compose, and moving to Compose made their code much simpler and easier to maintain. They also shared “We rewrote the button component in our app using Compose. Before it required 800 lines of code across three files plus 17 different XML files, and it is now down to a single Kotlin file with 300 lines of code. This is a 60% reduction in the Kotlin code alone“. The team at Zepeto has also been implementing Compose across many features, and are enjoying the experience, as “Compose simplified our UI layer logic, making it easier to understand code written by my colleagues.”
            It’s great to see how these teams experience faster development cycles, and also feel their UI code is more concise and readable. And they’re not the only ones. Since this year’s Google I/O, the number of top 1000 apps on Google Play using Compose has increased by 50%! To help your team follow in the footsteps of the teams at Lyft, Zepeto, and others, we published a guide on How to Adopt Compose for your Team. It outlines how and where to start, and shows the areas of development where Compose can bring huge added value.


            Compose, October ‘22 release

            Today we’re releasing a new stable version of Compose, with some exciting features and news.

            First of all, we’ve heard from you how it can be daunting to track versions across different artifacts that might go on different release schedules, so we’re now publishing, together with every Stable release of any of the Compose artifacts, a Bill of Materials, or BOM, to make your life easier.

            Our first BOM release, Compose October ‘22, brings support for Staggered Grids, drawing Text directly to Canvas, Pull to Refresh, as well as performance improvements and bug fixes.


            Compose Bill of Materials

            A BOM is a Maven module that declares a set of libraries with their versions. It will greatly simplify the way you define Compose library versions in your Gradle dependencies block, especially now that we moved the various Jetpack Compose libraries to independent versioning schemes. Instead of defining each version separately, which can become cumbersome and prone to errors when library versions start to differ, you now only need to define one BOM version and all Compose library versions will be extracted from that. We will publish a new version of the BOM every time a Compose artifact has a new stable release, so moving from stable release to stable release is going to be much simpler.

            dependencies {
                // Import the Compose BOM
                implementation platform('androidx.compose:compose-bom:2022.10.00')

                // Declare dependencies for the desired Compose libraries without versions
                implementation 'androidx.compose.foundation:foundation'
                androidTestImplementation 'androidx.compose.ui:ui-test-junit4'

                ...
            }


            We’ve added the instructions on how to add the Compose BOM to our Quick start guide. Note that you can still choose to define your dependencies using hard-coded versions. The BOM is added as a useful way to simplify dependencies and make upgrades easier.
                

            Modifiers on overdrive

            Behind the scenes, we’re always working on improving Compose performance. The October ‘22 release includes a major refactor of how Modifiers work under the hood. While you will not notice anything changing in the APIs, this refactor paves the way for greatly improving Modifier performance. Learn more about the rationale behind the changes, and what’s planned for the near future in the ADS talk Compose Modifiers deep dive.


            Popup & Dialog elevation change

            Accessibility is always a first-class citizen for Compose, and this release contains a behavior change that helps fix an Accessibility bug with Popups and Dialogs: their maximum elevation is decreased from 30dp to 8dp. Your app will be impacted only if it uses a custom dialog or popup implementation with an elevation higher than 8dp. The release notes contain more information about the change, including a way to override the new behavior as an interim solution (keep in mind that we always recommend using 8dp maximum when customizing popups or dialogs).


            New features

            We added a lot of new functionality to Compose. Here are some highlights:

            Compose Material 3 stable

            Today we also announce the first stable release of the Compose Material 3 library! You can build an app using Compose and theme it according to Material Design 3, our latest iteration of Material Design. Use Material Design 3 to further customize your app’s colors, typography and shapes to make your brand stand out! The library contains fresh and updated versions of many UI components, such as buttons, cards, checkboxes, switches, navigation bars, drawers, and many more, with support for others on its way. See a list of all the supported components in the documentation and learn more in this blog post.

            To help you adopt Material 3 check out our new migration guide with clear guidance on how Material 2 concepts translate to Material 3. The default template in Android Studio Flamingo now uses Material 3, to get you up and running in no time. We’ve also updated many of our sample apps, tutorials, templates, and codelabs to use Material 3 so you can learn as you go!

            New tools

            Developing your app using Jetpack Compose is much easier with the new and improved tools around it. We’ve added tons of new features to Android Studio to improve your workflow and efficiency:

            Android Studio Dolphin is the latest stable release, bringing you:

            • Animation Coordination
            • Multipreview annotations
            • Recomposition counts in Layout Inspector

            Android Studio Electric Eel contains beta features, like:

            • Live Edit (experimental)
            • Composition rendering highlighting
            • Configuring Preview devices
            • Live updates in Previews

            Android Studio Flamingo contains canary features such as:

            • New project templates use Compose and Material 3 by default
            • Live Edit turned on by default
            • Improved composition tracing to help you better inspect performance issues.

            Relay

            Today we also launch the first alpha version of Relay, a design-to-code solution for improving designer-developer collaboration. Designers create UI components using the Figma plugin, and developers use the Android Studio plugin to automatically use these components in their apps. The generated components are composable functions and can be integrated directly into your Compose app. Learn more about Relay in the documentation.


            Compose on WearOS, Large Screens and TV

            In July we released the first Stable version of Wear Compose, ready to build production apps. Compose for Wear OS is our recommended approach for building UIs for Wear OS apps. We’ve included over twenty Compose UI components that were designed specifically for Wearables, like TimeText, PositionIndicator, and ScalingLazyColumn.

            We’re also continuing to make it easier to design, develop, and test apps for large screens such as foldables, tablets, and Chrome OS. The material3-window-size-class library graduated to Stable, giving you a set of opinionated viewport breakpoints to work with. Large screen designs often contain staggered grids, and the addition of LazyHorizontalStaggeredGrid and LazyVerticalStaggeredGrid will help implement these.



            Feedback from the Android community always moves us forward. With your input we have updated our roadmap, focusing on areas that will help you implement Compose successfully. We’re now focusing on supporting more advanced use cases, covering more Material 3 components, improving platform support, tooling and performance.


            New and updated guidance

            No matter where you are in your learning journey, we’ve got you covered! We added and revamped a lot of the guidance on Compose:

            Compose Camp

            Running from September through December is a world-wide community-organized event series called Compose Camp! With both a beginner and an experienced track, developers of all levels can join Compose Camp to learn together with others. We already see lots of traction, with many videos being posted by GDGs and GDSCs all over the globe, and many events hosted on our Community platform.


            Happy Composing!

            We hope that you’re as excited by these developments as we are! If you haven't started yet, it's time to learn Jetpack Compose and see how your team and development process can benefit from it. Get ready for improved velocity and developer productivity. Happy Composing!

            Lyft reduced their code for UI components by as much as 60% using Jetpack Compose

            Learn why Lyft plans to shift entirely to Compose for future feature development

            Lyft reduced their code for Ul components by as much as 60% using Jetpack Compose

            Lyft, one of the largest ride-sharing companies in the U.S., is practically synonymous with one-tap transportation. Lyft has far outgrown its ride-hailing beginnings to now include everything from delivery services to additional modes of transportation such as bikes and scooters. With more than 50 million downloads on Google Play, Lyft’s engineers are always exploring new ways to streamline the product's features and functionality to improve the user experience.

            To keep up with the modern trends in mobile development, multiple teams at Lyft used Jetpack Compose to replace some of their legacy frameworks, reduce boilerplate code, and streamline their workflow. They also used it for feature rollouts and have benefited from the implementation.

            Less code, easier UI feature rollouts

            Lyft engineers adopted Compose for a UI overhaul and used a plugin framework that allowed developers to break down features into self-contained reusable modules. “Over 90% of all new feature code is now developed in Compose,” said Anton Tananaev, staff Android engineer at Lyft. This is in large part because Compose makes implementing new features a faster—and easier—process for engineers.

            Lyft has a unified design across its web and mobile apps as well as a Figma library of components, making it quick and easy to develop new UI features using those building blocks. Lyft's internal UI framework, called Lyft Product Language (LPL), allows them to easily use their unified design system across Android, iOS, and the web. The LPL includes common UI components, like visual elements within the app, and more complex panels and dialogs. To ensure Lyft’s riders and drivers have the best user experience, this design system is implemented individually on each platform. Compose is built with the flexibility to support Material Design, custom design systems, and everything in between, so Lyft was able to easily build these UI components to meet their custom visual requirements. On top of that, using Compose instead of views has dramatically decreased the lines of code required. A button component on the Lyft app has gone from around 800 lines of code across three files plus 17 different XML files down to a single Kotlin file with 300 lines of code. They were able to reduce the lines of code by nearly two-thirds of what was needed with Views!

            The team that’s working on the server-driven UI framework at Lyft also adopted Compose. Current systems only support static API response, but one key reason Lyft engineers prefer Compose is because it supports dynamic UI changes from the backend. Compose will automatically detect changes, so no additional client code is required to support dynamic content.

            A welcome improvement for engineers

            Moving over to Compose allowed Lyft to increase developer productivity and velocity. Not only do developers need to write less code in Compose than with Views, they find it easier to understand and maintain, and faster to ship any needed changes. This translates to more time developing new features for Lyft drivers and riders, and less time fixing old features.

            Lyft created their own unidirectional architecture, splitting the aspects of a UI into multiple pieces. That means they can pass the state needed for a UI independently of the actions to perform all while still taking advantage of other technologies used throughout their code like RxJava. Lyft's previous plugin system required several files with a lot of boilerplate code just to create a basic reusable component, but with Compose it can be a single file or even a simple Composable function in some cases.

            Developers at Lyft like Compose so much that nearly all new features are being developed in Compose, and they see it as the future of Android. Even in job interviews, Android engineer candidates show excitement at the possibility of using Compose and see it as a key indicator that Lyft is keeping current with modern Android technologies.

            Compose is clearly the future of Android development. It requires less code, and it's easier to understand and maintain.
Anton Tananaev Staff Android Engineer at Lyft

            Migrating to an easier-to-manage codebase

            Compose is fully interoperable with Views, so developers can build UI with as much or as little Compose as they’d like. The Lyft team enjoyed using Compose so much, however, that the engineers plan on migrating to Compose for nearly all of their features and are working on a plan to officially deprecate any new XML layouts so they can continue taking advantage of the benefits across the different parts of the app.

            “Compose is clearly the future of Android development, so the sooner we transition the better,” said Anton, “It requires less code, and it’s easier to understand and maintain.”

            Streamline your feature code with Compose

            Learn how you can improve feature coding with Jetpack Compose.

            ZEPETO plans to migrate at least 80% of the app’s UI to Jetpack Compose

            ZEPETO is a 3D social universe built by NAVER Z with more than 300 million users in over 200 countries. Those users can create unique avatars, foster friendships, and explore virtual realms of their own design. ZEPETO commits itself to creating spaces that prioritize the user’s experience. For its engineers, that meant making the switch to Jetpack Compose, Android’s modern toolkit for building native UI.ZEPETO plans to migrate at least 80% of the app's UI to Jetpack Compose

            Embracing Jetpack Compose

            ZEPETO was originally designed and developed using Views, Unity and OpenGL, but today 20% of the UI originally written in Views has been rewritten with Jetpack Compose. ZEPETO’s developers began to sequentially integrate the toolkit knowing it would resolve a number of recurring engineering friction points. With the Views system, implementing custom UI with some specific shapes, such as sliders or switches, required implementing the onDraw method with a Canvas. Jetpack Compose allows ZEPETO’s developers to implement these types of UI in Kotlin without needing to implement custom classes, simplifying the process and eliminating the extra steps required.

            Cleaning up the codebase

            With Jetpack Compose, ZEPETO’s developers rewrote complex UI features. They built a design system that helped organize fonts and sizes in a more intuitive way, improving maintainability, efficiency, and the UX. “Using Compose, we rewrote parts of the app where the UI is relatively complex and various business logics exist, such as the character shop, gift giving, and face decoration,” said Android Developer Hojung Kim. In places like the pager and grid areas of the character shop, Composable functions helped reduce the amount of code by more than 10%.

            The ZEPETO team decided to migrate its common dialog components to Compose too. This enabled its engineers to use the desired type of dialog needed throughout all parts of the app. “Each element of the common dialog can now be made into a component, making it possible to create a common dialog, just like assembling a Lego,” said Juhyung Park, Android Developer at ZEPETO. Modularizing the code allowed the engineers to implement commonly used app components much faster than before. By migrating these dialog components, the team was able to clean up 1600+ lines of code, making it much more readable, understandable, and significantly easier to maintain.


            Refining the developer experience

            Jetpack Compose drastically increased the efficiency of previewing, developing, and implementing UI by allowing developers to reuse and share UI elements. ZEPETO developers have already created more than 230 preview functions to effortlessly test and debug features across the application.

            It was also relatively easy for the team to learn how to use Jetpack Compose. “It doesn’t take long for developers familiar with the existing Android View system to reach a level where they can use Compose in actual practice,” said Hojung.

            We rewrote the Character Shop feature in Compose. It was much faster to write it in Compose, and we reduced the amount of code by over 10% ≫
Hojung Kim Android developer, ZEPETO

            Moving forward with Compose

            The ZEPETO team is motivated by Google’s increasing support for Jetpack Compose as it’s clear Compose is a huge priority for Google. They’re excited about how Google is integrating more Android APIs with Compose, and are looking forward to further development of the toolkit.

            Several of ZEPETO’s features are now built with Jetpack Compose alongside the graphics built with Unity and OpenGL, such as the character shop, video and photo editors, and dialog components, but the team doesn’t plan to stop there. Given the improvements they’ve seen with development speed, code maintenance, and code reduction, they’ll continue migrating existing screens and building new features with Compose. “In the long run,” finished Hojung, “more than 80% of the UI will be written with Compose,” with the remaining UI and graphics with Unity and OpenGL.


            Optimize your app

            Learn how you can upgrade your UI development with Jetpack Compose.