Tag Archives: Android Development

A Smoother Ride: Android Emulator Stability and Performance Updates

Posted by Neville Sicard-Gregory – Senior Product Manager, Android Studio


Looking for a more stable, reliable, and performant Emulator? Download the latest version of Android Studio or ensure your Emulator is up to date in the SDK Manager.

A split screen shows Kotlin code on the left and the corresponding Android app display on the right in Android Studio. The app displays the Google Play Store, Photos, YouTube, Gmail, and Chrome icons.

We know how critical the stability, reliability, and performance of the Android Emulator is to your everyday work as an Android developer. After listening to valuable feedback about stability, reliability, and performance, the Android Studio team took a step back from large feature work on the Android Emulator for six months and started an initiative called Project Quartz. This initiative was made up of several workstreams aimed at reducing crashes, speeding up startup time, closing out bugs, and setting up better ways to detect and prevent issues in the future.

Improved stability and reliability

A key goal of Project Quartz aimed to reduce Emulator crashes, which can frustrate and block developers, decreasing their productivity. We focused on fixing issues causing backend and UI crashes and freezes, updated the UI framework, updated our hypervisor framework, and our graphics libraries, and eliminated tech debt. This included:

    • Moving to a newer version of Qt, the cross-platform framework for building the graphical user interfaces of the Android Emulator, and making it stable on all platforms (as of version 34.2.13/ This was also a required change to ensure things like Google Maps and the location settings UI continued to work in the Android Emulator.
    • Updating gfxstream, the graphics rendering system used in the Android Emulator, to improve our graphics layer.
    • Adding more than 600 end-to-end tests to the existing pytests test suite.

As a result, we have seen 30% fewer crashes in the latest stable version of Android Studio, as reported by developers who have opted-in to sharing crash details with us. Along with additional end-to-end testing, this means a more stable, reliable, and higher quality experience with fewer interruptions while using the Android Emulator to test your apps.

A horizontal bar graph showing performance times of different versions of the Android emulator in milliseconds

This chart illustrates the reduction in reported crashes by stable versions of the Android Emulator (newer versions are at the top and shorter is better).

We have also enhanced our opt-in telemetry and logging to better understand and identify the root causes of crashes, and added more testing to our pre-launch release process to improve our ability to detect potential issues prior to release.

Improved release quality

We also implemented several measures to improve release quality, including increasing the number and frequency of end-to-end, automated, and integration tests on macOS, Microsoft Windows, and Linux. Now, more than 1,100 end-to-end tests are ran in postsubmit, up from 500 tests in the past implementation, on all supported operating system platforms . These tests cover various scenarios, including (among other features) different Android Emulator snapshot configurations, diverse graphics card considerations , networking and Bluetooth functionality, and performance benchmarks between Android Emulator system image versions.

This comprehensive testing ensures these critical components function correctly and translates to a more reliable testing environment for developers. As a result, Android app developers can accurately assess their app's behavior in a wider range of scenarios.

Reduced open issues and bugs

It was also important for us to reduce the number of open issues and bugs logged for the Android Emulator by addressing their root cause and ensuring we cover more of the use cases you run into in production. During Project Quartz, we reduced our open issues by 43.5% from 4,605 to 2,605. 17% of these were actively fixed during Quartz and the remaining were closed as either obsoleted or previously fixed (e.g. in an earlier version of the Android Emulator) or duplicates of other issues.

Next Steps

While these improvements are exciting, it's not the end. We will continue to build on the quality improvements from Project Quartz to further enhance the Android Emulator experience for Android app developers.

As always, your feedback has and continues to be invaluable in helping us make the Android Emulator and Android Studio more robust and effective for your development needs. Sharing your metrics and crashdumps is crucial in helping us understand what specifically causes your crashes so we can prioritize fixes.

You can opt-in by going to Settings, then Appearance and Behavior, then System Settings, then Data Sharing, and selecting the checkbox marked ‘Send usage statistics to Google.'

The Android Studio settings menu displays the Data Sharing settings page, where 'Send usage statistics to Google' option is selected.

Be sure to download the latest version of the Android Emulator alongside Android Studio to experience these improvements.

As always, your feedback is important to us – check known issues, report bugs, suggest improvements, and be part of our vibrant community on LinkedIn, Medium, YouTube, or X. Together, we can create incredible Android experiences for users worldwide!

Now’s the time to learn Android development with Jetpack Compose!

Posted by Murat Yener, Developer Relations Engineer

We are thrilled to announce that the full Android Basics with Compose course is now available. Whether you're a beginner with no programming experience, or a developer looking to learn Jetpack Compose and brush up on their Android development skills, it's a great time to start learning.

This course is designed to teach you how to create Android apps using Jetpack Compose, Android's recommended modern toolkit that simplifies and accelerates Android UI development. Along the way, you'll explore fundamentals of the Kotlin programming language, Android app architecture, and commonly used Jetpack libraries. We also include a unit on Views-Compose interoperability so you can apply your Compose skills when you are working on an existing app built with the legacy View-based UI toolkit.

Android Basics with Compose is divided into 8 units, each covering a different aspect of Compose and Android development. Some of the topics covered are:

  • Fundamentals of the Kotlin programming language
  • Building basic user interfaces with Compose
  • Working with data and state in Compose
  • Using navigation to build apps with multiple screens
  • Persisting data using Room and DataStore
  • Fetching remote data and images
  • Scheduling tasks with WorkManager
  • Using Compose and Views side-by-side in the same app

Each unit is packed with hands-on exercises, quizzes, and open-ended projects to help you solidify your understanding of the content.

Image of five phone screens side by side displaying different modules in Android Basics with Compose

You'll learn how to test what you built and use Android Studio tools to further debug and troubleshoot your app. Plus you will earn badges to showcase your achievement in your Google Developer Profile!

Image of 17 different badges that can be earned to showcase your acheivement in your Google Developer Profile

Compared with our previous training course, Android Basics in Kotlin, we have expanded our coverage of Kotlin language basics. We used the same app concepts as in the older course so you can compare the same app built with Compose and legacy Views side-by-side.

Image if two phone screens side by side showing the 'unscramble the word' concept being used in Android Basics in Kotlin course (left) and in Jetpack Compose for Android Developers (right)

If you are already familiar with developing Android apps with Kotlin and are only looking to learn Compose, you may also want to check out the Jetpack Compose for Android Developers course.

The Android Basics with Compose course is available online and self-paced, making it easy for you to learn at your own pace and on your own schedule. This course provides up-to-date information and guidance on each topic, and all apps are updated with our latest architectural best practices.

We hope you enjoy the course and find it valuable in your journey as an Android developer. Happy coding, and please share what you've built on social media, using #AndroidBasics!

Announcing Kotlin support for protocol buffers

Posted by Deanna Garcia and Louis Wasserman - Software Developers, and Developer Advocate, James Ward

Google’s commitment to Kotlin

At Google, we’re investing deeply in the Kotlin language and ecosystem. Android development is now Kotlin first, our engineering teams work on language evolution through the Kotlin Foundation, and inside of Google we’re using Kotlin more and more to build our backend services. We love Kotlin for its expressiveness, safety, simple async support through coroutines, and easy bidirectional interoperability with the Java programming language.

Kotlin for protocol buffers

Last year, we open sourced Kotlin support for gRPC, the open source Remote Procedure Call (RPC) framework that powers thousands of microservices at Google. We’re excited to deepen our investment in the Kotlin language with official support for Kotlin in the open source Protocol Buffers project (a.k.a. “protos”), Google’s platform-neutral, high-performance data interchange format. From a proto definition, you can use the new built-in Kotlin support in the proto compiler to generate idiomatic Kotlin Domain Specific Languages (DSLs).

For example, here’s a simple protocol buffer message representing a series of dice rolls:

message DiceSeries {
message DiceRoll {
int32 value = 1; // value of this roll, e.g. 2..12
string nickname = 2; // string nickname, e.g. "snake eyes"
}

repeated DiceRoll rolls = 1;
}

In the Java language, constructing a series of dice rolls might look like this:

DiceSeries series = DiceSeries.newBuilder()
.addRoll(DiceRoll.newBuilder()
.setValue(5))
.addRoll(DiceRoll.newBuilder()
.setValue(20)
.setNickname("critical hit"))
.build()

With this release, protos offer an expressive set of DSL factory methods that make this code elegant and idiomatic in Kotlin. Here is the equivalent dice roll code written using the new Kotlin proto bindings:

val series = diceSeries {
rolls = listOf(
diceRoll { value = 5 },
diceRoll {
value = 20
nickname = "critical hit"
}
)
}

The Kotlin version uses Kotlin type-safe builders, which makes it concise and removes the need to explicitly call a build method. Note that this works with both the proto compiler’s standard and "proto lite" modes, the latter generating smaller, higher performance classes which are more suitable for Android.

Note: Since protos use the get prefix for their fields and Kotlin recognizes that as a property, reading from a proto already works smoothly from Kotlin as if the proto were a data class.

val totalRolls = series.rolls.map { it.value }.sum() // 5 + 20 = 25

Kotlin Protos and gRPC Kotlin

The new Kotlin Protos work great with gRPC Kotlin providing a concise syntax for messages and services. Let's walk through a basic sample.

Here is a basic "Greeter" gRPC service proto:

service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
string name = 1;
}

message HelloReply {
string message = 1;
}

Check out the full example proto source.

The non-blocking server can be implemented concisely, taking advantage of the Kotlin proto builders:

class HelloWorldService : GreeterCoroutineImplBase() {
override suspend fun sayHello(request: HelloRequest) = helloReply {
message = "hello, ${request.name}"
}
}

Check out the full example server source.

The non-blocking client also can take advantage of the type-safe Kotlin builders with concise syntax:

val stub = GreeterCoroutineStub(channel)
val request = helloRequest { name = "world" }
val response = stub.sayHello(request)
println("Received: ${response.message}")

Check out the full example client source.

Those code examples really illustrate how concise the syntax is, which means less boilerplate to write and less for our brains to parse as we try to read the code. What isn't evident in these examples is how nice the experience is when writing high-performance RPC code. Thanks to static typing and the type-safe builders, you can easily code-complete your way through code that is "correct" in-that the types / properties are consistent with the protos.

The protobuf compiler (protoc) now has built-in support for generating Kotlin code. A bit of configuration is needed to tell your build tool (Maven, Gradle, etc) to do that. For Gradle builds it looks like:

protobuf {
// omitted protoc and plugins config
generateProtoTasks {
all().forEach {
// omitted plugins config
it.builtins {
id("kotlin")
}
}
}
}

Check out the full example Gradle build.

Give the complete gRPC Kotlin example a spin and also explore other aspects like the Android client and native client (built with GraalVM Native Image) which both use the lite protos. For an example Maven project check out the grpc-hello-world-mvn sample.

For examples that can be deployed with a couple clicks on Google Cloud Run (a fully managed serverless platform) check out: grpc-hello-world-gradle, grpc-hello-world-streaming (server push), or grpc-hello-world-bidi-streaming (bi-directional streaming).

Learn More

To learn more about Kotlin protos check out these docs:

Let us know how it goes and if you have any Kotlin proto issues by filing them within the official protobuf project.

Additional thanks to Adam Cozzette, Brent Shaffer, David Jones, David Winer, Jeff Grimes, John Pampuch, and Kevin Bierhoff for their contributions to this release!

Performance insights for Games, powered by Android Performance Tuner

Posted by Dan Galpin, Developer Advocate

Android vitals is the destination for managing your app's technical quality. Over 80,000 developers take advantage of its performance and stability metrics every month.

As part of our work to help you deliver better game experiences to more Android users, we're introducing Android Performance Tuner - a new library in the Android Game SDK that unlocks game performance insights in Android Vitals. This gives you a scalable way to measure and optimize your frame rate and graphical fidelity across the whole Android device ecosystem.

Unity Boat Attack Sample with Different Optimizations

Unity Boat Attack Sample with Different Optimizations

Once you have integrated Android Performance Tuner into your game and published it on Play, you'll be able to see how it performs across real users and devices with the following new features in Android vitals.

Frame rate performance

Frame Rate Performance by Quality Level and Device Model

Frame Rate Performance by Quality Level and Device Model

We chart the frame time distribution across your users’ devices, broken down by quality levels that you have implemented in your game, so you can see how specific device models or hardware specifications are performing on each quality level.

Performance issues

We also analyze your performance data to help determine the likely cause of issues, so you can differentiate between problems associated with specific hardware and problems with specific screens or levels in your game. You annotate your code to give contextual information about what your game is doing at that point. This gives you full control over the granularity of the insights.

Top Device Model/Annotation Issues

Top Device Model/Annotation Issues

We call out the top device model issue as well as the top game-specific issue to give you clear guidance on what's most important.

Underperforming Device Models by GPU

Underperforming Device Models by GPU

You can drill down to see a breakdown of underperforming device models by different specs, such as GPU and SoC. This allows you to decide whether you can work at the GPU or SoC-level to optimize performance. Alternatively, you may decide to change quality levels, rather than work at the device model level.

Device Model Impact, User Impact, GPU time

Device Model Impact, User Impact, GPU Time

You can also see the full list of device models, along with the number of affected user sessions and frame time, to help you prioritize device-specific changes. As well as total frame time, we also show you GPU time to help determine whether the device is GPU bound or has another performance problem, such as being CPU or I/O bound. All data in the device model table can be exported for further analysis and action planning.

Opportunities to make a good experience great

We can also help identify opportunities — places where you could potentially provide users with a better experience by giving them a higher quality level, enabling more advanced graphical features. Frame Time Performance with Opportunities

Frame Time Performance with Opportunities

The devices on the far left are more than meeting the frame times for smooth performance. You can drill down to see stats by device model and specification to see if there is an opportunity to improve the graphical fidelity across a wide range of devices.

Available (almost) everywhere

The Android Performance Tuner is intended to work across over 99% of the Android device ecosystem. You can get these insights on any Android devices around the world, from Android 4.1 (API 16) onwards.

Integrating Android Performance Tuner

Whether you have your own game engine or are using a third-party game engine, we're doing our best to make integration easy. The Android Performance Tuner relies on tick functions being called each frame. Within the library, this tick information is aggregated into histograms, which are periodically uploaded through an HTTP endpoint, so your game will need to have the internet access permission.

With our plugin for the Unity platform, you can collect frame ticks from Unity 2017.4 onwards. Unity 2019.3.14+ enables the collection of higher-fidelity performance information.

If you're doing a native source code level engine integration, we strongly recommend integrating the Frame Pacing API from the Android Game SDK to get the highest quality information. The Frame Pacing API will give you smoother frame rates and improved support for high-refresh rate displays, so it's worth integrating on its own.

Unreal 4.25+ integrates the Frame Pacing API. You enable it by adding a.UseSwappyForFramePacing=1 to the Android_Default profile to activate it for all Android devices.

Within Unreal or your native engine integration, you pass in the Swappy_injectTracer function from the Frame Pacing API at initialization to enable automatic frame time recording.

void InitTf(JNIEnv* env, jobject activity) {
   SwappyGL_init(env, activity);
   swappy_enabled = SwappyGL_isEnabled();
   TFSettings settings {};
   if (swappy_enabled) {
       settings.swappy_tracer_fn = &SwappyGL_injectTracer;
   }
…
}

Enabling Frame Time Recording in the Android Performance Tuner for your Engine

In Unity, we recommend activating Optimized Frame Pacing within the Unity settings (Unity 2019.3+ only), but Frame Pacing isn't required in Unity to use the Android Performance Tuner.

Activating Optimized Frame Pacing in Unity 2019.3

Activating Optimized Frame Pacing in Unity 2019.3

Providing contextual information

Next, you want to define annotations to give contextual information about what your game is doing when a tick is recorded, such as:

  • Current game level
  • Loading a specific scene
  • A "big boss" or other complex rendered item is on the screen
  • Relevant game state information

Annotation Parameters

If you're using Unity with the Android Performance Tuner plugin, you'll automatically get a scene annotation that maps to the current scene being played. The LoadingState annotation can be easily hooked up to your scripts, and you can define additional annotations within the plugin editor UI.

Annotation Parameters within the Unity Editor from the Android Performance Tuner Plugin

Annotation Parameters within the Unity Editor from the Android Performance Tuner Plugin

To pass annotation parameters from within your own game engine, you define a protocol buffer message that contains all of these annotations, such as loading state, level or scene, etc.

Fidelity Parameters and Quality Levels

You also define fidelity parameters and associate them with quality levels that your game reports back. These can be used for anything that you use in your game to reduce the complexity of the scene, such as texture quality, draw distance, particle count, post-processing effects, shadow resolution, etc. In the native integration, you define these parameters using a protocol buffer.

import "tuningfork.proto"
message FidelityParams {
  int32 texture_quality_level = 1;
  int32 shadow_resolution = 2;
  float terrain_details_percent = 3;
  int32 post_processing_effects_level = 4;
}

Example FidelityParams Proto Definition for an In-house Engine

Then, you create up to fifteen sets of quality levels as a set of values defined by the FidelityParams message, which allows the Android Performance Tuner to track its metrics against your quality data. You can create both fidelity parameters and quality levels in the Unity editor interface provided by the Android Performance Tuner for Unity plugin.

Testing your integration

We've created the Tuning Fork Monitor app to act as a local server and display data from an Android Performance Tuner-enabled app. You can call EnableLocalEndpoint() in the Android Performance Tuner Unity plugin on a development build to enable local testing. In your native integration, you set the endpoint_uri_override in the Android Performance Tuner settings.

Once local tests look great, you then enable the Android Performance Parameters API in the Google Cloud Console to test end-to-end.

Available Now

We're committed to helping you bring the best version of your game to the widest number of users and devices in the Android ecosystem. Android Performance Tuner within the Android Game SDK, the Unity plugin, and Performance Insights within Android Vitals are all available now. You can refer to our documentation for a walk through of the process for native and Unity integrations.

Google Play Trust and Safety Update

Posted by Krish Vitaldevara, Director of Product Management Trust & Safety, Google Play

As part of our continuing efforts to enhance user trust and safety across Google Play, we regularly examine our policies to ensure a positive experience for developers and users. Today we are announcing policy updates that give users more control over their data, tighten subscription policies, and help prevent deceptive apps and media getting onto the Play Store.

We understand that many of you are adjusting to or actively supporting efforts in response to the current unprecedented circumstances. We want to assure you that we are mindful and supportive of those efforts, and have taken steps to minimize the potential short-term impact of these changes. You can read more about that in this blog post which shares resources for developers navigating the current context. We also wanted to briefly highlight two of the more impactful policies announced today.

More transparent subscription offers

Subscriptions continue to grow in popularity on Play; however, we hear user feedback that it isn’t always clear what you are signing up for. The goal of this policy update is to ensure users understand the subscription offer, the terms of free trials and introductory offers, and how to manage their subscription, including cancellation.

This blog post goes into more detail about the changes and gives examples of best practices and common violations. Developers have until June 16th to make any changes to their offer page.

Limiting unnecessary location access

Users consistently tell us that they want more control over their location data and that we should take every precaution to prevent misuse. Android users have always needed to grant explicit permission to any app that wants access to their location data. In Android 11, we’re granting additional user controls with the ability to grant a temporary “one-time” permission.

In February, we announced we would require that developers get approval if they want to access background location in their app. This ensures that only apps that really need access for core functionality can ask users for permission. This policy is now live and we encourage all developers who access location to view it.

We realize complying with certain aspects of this policy may require work for some developers so we are giving you an extended timeline to make changes. We suggest that you review location best practices and evaluate whether you have appropriate disclosures, and really need background location; however, no action will be taken for new apps until August 2020 or existing apps until November 2020. Additional details can be found in this help center article and we’ll keep you updated if processes or timelines change. Thanks for your continued support in making Google Play a trustworthy and valuable experience for everyone.

How useful did you find this blog post?

Google for Games Developer Summit March 2020

Posted by Greg Hartrell, Head of Product Management, Games on Android & Google Play

"Developer Summit Google for Games " with game illustration.

While we're sorry we didn't get to see you all in person at GDC, we hope you are all staying healthy and safe. As many of us look to press on with work as much as possible, we’d like to share with you what our teams have been working on at the digital Google for Games Developer Summit. We couldn’t be happier with the continued growth of the vibrant Android gaming ecosystem. In fact, Android remains the world's most popular mobile platform with more than 2.5 billion monthly active devices and great news for game developers, we’re seeing more than 1.4 trillion minutes played per month in your games on Google Play. It’s important to us that our platforms are highly useful to every kind of game developer, so our payment system helps games monetize in more than 65 countries. Moreover, we offer our users more than 275 local forms of payment, including more than 180 carrier billing options, with gift cards sold in over 900 thousand unique retail locations worldwide.

Across Android and Google Play, our mission is to deliver the best platform to build, discover, and experience games. Specifically, we’re working on ways to help you increase the reach of your games and manage the fragmentation of the Android ecosystem. We’re also focused on helping you access a wider player base, once you’ve made a great game and are ready to get it out there. Last year, we shared that we’re investing heavily in our games efforts to address your challenges in these areas, and now we are excited to share several new tools and services built specifically with game developers in mind.

Catch up on everything shared at g.co/gamedevsummit.

New Android tools for mobile game development

A major area of investment for us has been making it easier for developers to build and optimize games for Android. Here’s a round-up of several new tools we’re releasing:

  • Android Studio Profilers: We’ve overhauled our Android Studio System Trace profiler to allow you to inspect and visualize in fine detail how your code is being executed. We also added native memory profiling capabilities so you can see how your game is allocating memory and find memory leaks. Download Android Studio 4.1 Canary and watch the session.
  • Android Game Development Extension for Visual Studio: We’re introducing a new tool to make it easy to add Android support for your cross-platform games. This integrates easily with existing Visual Studio-based workflows so now you can conveniently generate APKs, deploy to Android devices or an emulator, and debug your Android game from within Visual Studio. Apply for the developer preview and watch the session.
  • Android GPU Inspector: Our new Android GPU Inspector enables you to look deeply into an Android GPU and see detailed information about your game’s render stages and GPU counters. Now graphics engineers are empowered with information and insights to optimize their game for better frame rates and more battery life. Apply for the developer preview and watch the session.
  • Game Package Registry for Unity by Google: Our new package registry consolidates various Google APIs, starting with Google Play Billing, Android App Bundles, Play Asset Delivery, Play Instant, and Firebase for Games, all in one place. Learn more and watch the session.
  • Crytek announces Android support: CRYENGINE is known as a high performance game engine for PCs and game consoles and will be adding a full Android pipeline to their engine this summer. Learn more.

New ways to reach more devices & users

We’ve been working to help developers scale their reach to a growing player-base across the Android ecosystem. Today, we’re introducing a few new tools to help your development process and provide greater insights into your game’s performance.

  • Google Play Asset Delivery: Introducing a new set of delivery features for games services, building on our App Bundle infrastructure to give you free, dynamic delivery of the right game assets to the right devices at the right time. All of this allows players to get into your game faster while assets are being downloaded, while you cut the costs of hosting and delivering d game resources. Learn more and watch the session.
  • Android vitals native crash symbolication: Now you can debug your native crashes more easily with support for native symbols in Play Console. Simply upload your native debug symbols to get the benefits in Android Vitals. Apply for the open beta and watch the session.
  • Android vitals performance insights with Android Performance Tuner: We’re making it possible to optimize your frame rate and fidelity across many devices at scale with new performance insights in Android vitals. For those in our developer preview, you can unlock this by integrating the new Android Performance Tuner into your game: a new library in the Android Game SDK. Apply for the developer preview and watch the session.
  • Play Billing Library 2 for Unity developers: Game developers using Unity can now access all of Play Billing Library 2's features, such as allowing users to pay with cash and surfacing IAPs outside of the game. This is the best way for Unity developers to prepare for Play’s Billing Library version requirements in 2021. Learn more.

New ways to reach more devices and win go-to-market

The Google Play store is shifting to be more gameplay centric by showing more visuals that demonstrate gameplay and a new system of tags to help users learn more about specific game traits and aid in exploration. Learn how you can ensure your game is of high-quality and leverage various features and new services to help you succeed in your go-to-market activities.

  • Emphasis on quality: We continue to emphasize high quality gaming experiences across Google Play, to encourage immersive gameplay with strong technical performance and being free of crashes. Learn more.
  • Pre-registration: Hundreds-of-millions of players use pre-registration campaigns on Google Play each year, making it an effective way to expand the reach on launch. We’ll soon be rolling out day 1 auto-installation for all pre-registration games, to help you build early consumer awareness and capture pre-launch demand.
  • Play Pass: Late last year we launched Play Pass in the US market as a subscription service providing users with access to hundreds of great apps and games on Google Play, completely free of ads and in-app purchases. Learn more and express interest.

Thanks for your support in continuing to build incredible games. Make sure to try some of the new tools and services we just released and catch the full playlist of mobile developer sessions. If you’re interested in sharing feedback to help shape the development of cutting edge features, apply to join our developer preview programs from Android and Google Play. You can also learn about all of the offerings we have to help game developers building on Android at d.android.com/games.

How useful did you find this blog post?

Handling Nullability in Android 11 and Beyond

Posted by David Winer, Kotlin Product Manager

Android blog banner

Last May at Google I/O, we announced that Android was going Kotlin first, and now over 60% of the top 1000 Android apps use Kotlin. One feature we love about Kotlin is that nullability is baked into its type system — when declaring a reference, you say upfront whether it can hold null values. In this post, we’ll look at how the Android 11 SDK does more to expose nullability information in its APIs and show how you can prepare your Kotlin code for it.

How does nullability in Kotlin work?

When writing code in Kotlin, you can use the question mark operator to indicate nullability:

KOTLIN

var x: Int = 1
x = null // compilation error

var y: Int? = 1
y = null // okay

This aspect of Kotlin makes your code safer — if you later call a method or try to access a property on a non-null variable like x, you know you’re not risking a null pointer exception. We hear over and over again that this feature of Kotlin gives developers more peace of mind and leads to higher quality apps for end users.

How does nullability work with the Java programming language?

Not all of your (or Android’s) APIs are written in Kotlin. Fortunately, the Kotlin compiler recognizes annotations on Java programming languages methods that indicate whether they produce nullable or non-nullable values. For example:

JAVA

public @Nullable String getCurrentName() {
   return currentName;
}

The @Nullable annotation ensures that when using the result of getCurrentName in a Kotlin file, you can’t dereference it without a null check. If you try, Android Studio will notify you of an error, and the Kotlin compiler will throw an error in your build. The opposite is true of @NonNull — it tells the Kotlin compiler to treat the method result as a non-null type, forbidding you from assigning that result to null later in your program.

The Kotlin compiler also recognizes two similar annotations, @RecentlyNullable and @RecentlyNonNull, which are the exact same as @Nullable and @NonNull, only they generate warnings instead of errors1.

Nullability in Android 11

Last month, we released the Android 11 Developer Preview, which allows you to test out the new Android 11 SDK. We upgraded a number of annotations in the SDK from @RecentlyNullable and @RecentlyNonNull to @Nullable and @NonNull (warnings to errors) and continued to annotate the SDK with more @RecentlyNullable and @RecentlyNonNull annotations on methods that didn’t have nullability information before.

What’s next

If you are writing in Kotlin, when upgrading from the Android 10 to the Android 11 SDK, you may notice that there are some new compiler warnings and that previous warnings may have been upgraded to errors. This is intended and a feature of the Kotlin compiler — these warnings tell you that you may be writing code that crashes your app at runtime (a risk you would miss entirely if you weren’t writing in Kotlin). As you encounter these warnings and errors, you can handle them by adding null checks to your code.

As we continue to make headway annotating the Android SDK, we’ll follow this same pattern — @RecentlyNullable and @RecentlyNonNull for one numbered release (e.g., Android 10), and then upgrade to @Nullable and @NonNull in the next release (e.g., Android 11). This practice will give you at least a full release cycle to update your Kotlin code and ensure you’re writing high-quality, robust code.

1. Due to rules regarding handling of annotations in Kotlin, there is currently a small set of cases where the compiler will throw an error for @Nullable references but not for @RecentlyNullable references.

Java is a trademark of Oracle and/or its affiliates.

Kotlin/Everywhere – it’s a wrap!

Posted by Florina Muntenescu, Developer Advocate (@FMuntenescu)

At Google I/O 2019 we announced that Android development will become increasingly Kotlin-first. Together with JetBrains, we also launched Kotlin/Everywhere - a global series of community led events focusing on the potential of using Kotlin everywhere; on Android, servers, web front-end and other platforms.

Kotlin/Everywhere events took place from May through December and we want to thank everyone for getting involved

?‍??‍?30,000+ developers participated in-person at Kotlin/Everywhere events

??200,000 views of live-streams and event recordings like Kotlin/Everywhere Bengaluru, Minsk, Chicago, Buenos Aires and more.

? 500+ events: from short evening meetups, half-day sessions, and full day events, to Kotlin/Everywhere tracks at larger events like DevFests, or even StudyJams that spanned several weeks.

?~30 speakers from Google and JetBrains gave ~70 talks at events around the world.

? 85+ countries: from United States to Chile, Kenya, Greece, Taiwan, New Zealand and so many more, with some countries hosting 1-2 events to some hosting dozens: Nigeria - 38, China - 27, India - 25 just to name a few.

? Many of the resources used or created for Kotlin/Everywhere by Google and JetBrains are available online:

General Kotlin:

Kotlin in Android:

Kotlin in Google Cloud Platform:

Multi-platform Kotlin:

We’re grateful for this engagement with Kotlin from communities around the world, as well as for all the organisers, speakers and attendees who made these events possible! To participate in more Kotlin events, check out JetBrains’ KotlinConf’19 Global initiative, happening through March 2020.

With all of the resources available, there’s never been a better time to adopt Kotlin… Everywhere!

Android’s commitment to Kotlin

Posted by David Winer, Kotlin Product Manager

Android and Kotlin banner

When we announced Kotlin as a supported language for Android, there was a tremendous amount of excitement among developers. Since then, there has been a steady increase in the number of developers using Kotlin. Today, we’re proud to say nearly 60% of the top 1,000 Android apps contain Kotlin code, with more and more Android developers introducing safer and more concise code using Kotlin.

During this year’s I/O, we announced that Android development will be Kotlin-first, and we’ve stood by that commitment. This is one of the reasons why Android is the gold partner for this year’s KotlinConf.

Seamless Kotlin on Android

In 2019, we focused on making programming in Kotlin on Android a seamless experience, with modern Kotlin-first APIs across the Android platform. Earlier this year, we launched a developer preview of Jetpack Compose, a modern UI toolkit for Android built using a Kotlin domain-specific language (DSL). We also incorporated coroutines into several of the flagship Jetpack libraries, including Room and Lifecycle. Finally, we brought Kotlin extensions (KTX) to even more major Google libraries, including Firebase and Play Core.

On the tooling side, we strengthened our commitment to Kotlin in Android Studio and the Android build pipeline. Significant updates to R8 (the code shrinker for Android) brought the ability to detect and handle Kotlin-specific bytecode patterns. Support was added for .kts Gradle build scripts in Android Studio, along with improved Kotlin support in Dagger. We worked closely with the JetBrains team to optimize support for the Kotlin plugin, and make the Kotlin editing experience in Android Studio fluid and fast.

Better Kotlin learning

This year we’ve also invested in quality Kotlin on Android learning content.

We released two free video learning courses in partnership with Udacity: Developing Android Apps in Kotlin and Advanced Android in Kotlin. This content was also released as the Codelab courses Android Kotlin Fundamentals and Advanced Android in Kotlin, for those who prefer text-based learning. The popular Kotlin Bootcamp for Programmers Udacity course was also published as a Codelabs course, helping provide a Kotlin foundation for non-Kotlin developers. Kotlin-based instructional Codelabs were also created for topics including Material Design, Kotlin coroutines, location, refactoring to Kotlin, billing in Kotlin, and Google Pay in Kotlin. It hasn’t been just about new content: we've updated Kotlin Codelab favorites to take advantage of important features such as coroutines.

Looking ahead

In 2020, Android development will continue to be Kotlin-first. We’ve been listening to your feedback, and will continue partnering with JetBrains to improve your experience with Kotlin.

This includes working with JetBrains to improve the Kotlin compiler over the next year. Our teams are making the compiler more extensible with a new backend, and making your builds faster with a significantly faster frontend. We’re also working with many of the largest annotation processors to make compilation faster for Kotlin code. You can also expect more Kotlin-first updates to Android, including more Jetpack libraries that make use of Kotlin features such as coroutines.

Thank you for letting us be part of your app development journey this year. We look forward to continuing the journey with you in 2020.

New! Learn How to Build Android Apps with Android Jetpack and Kotlin

Posted by Dan Galpin

Developing Android Apps with Kotlin, developed by Google together with Udacity, is our newly-released, free, self-paced online course. You'll learn how to build Android apps using industry-standard tools and libraries in the Kotlin programming language.

Android development fundamentals are taught in the context of an architecture that provides the scaffolding for robust, maintainable applications. The course covers why and how to use Android Jetpack components such as Room for databases, Work Manager for background processing, the Navigation component, and more. You'll use popular community libraries to simplify common tasks such as Glide for image loading, Retrofit for networking, and Moshi for JSON parsing. The course teaches key Kotlin features such as coroutines to help you write your app code more quickly and concisely.

As you work through the course, you'll build fun and interesting apps, such as a Mars photo gallery, a trivia game, a sleep tracker and much more.

Two mobile phones with flow chart in between depicting the difference between an over view and details.
Three screens for Android Navigation Component Trivia screen on mobile

This course is intended for people who have programming experience and are comfortable with Kotlin basics. If you're new to the Kotlin language, we recommend taking the Udacity Kotlin Bootcamp course first.

The course is available free, online at Udacity; take it in your own time at your own pace.

Come learn how to build Android apps in Kotlin with us at https://www.udacity.com/course/ud9012.