Tag Archives: Kotlin

Truth 1.0: Fluent Assertions for Java and Android Tests

Software testing is important—and sometimes frustrating. The frustration can come from working on innately hard domains, like concurrency, but too often it comes from a thousand small cuts:
assertEquals("Message has been sent", getString(notification, EXTRA_BIG_TEXT));
assertTrue(
    getString(notification, EXTRA_TEXT)
        .contains("Kurt Kluever <[email protected]>"));
The two assertions above test almost the same thing, but they are structured differently. The difference in structure makes it hard to identify the difference in what's being tested.
A better way to structure these assertions is to use a fluent API:
assertThat(getString(notification, EXTRA_BIG_TEXT))
    .isEqualTo("Message has been sent");
assertThat(getString(notification, EXTRA_TEXT))
    .contains("Kurt Kluever <[email protected]>");
A fluent API naturally leads to other advantages:
  • IDE autocompletion can suggest assertions that fit the value under test, including rich operations like containsExactly(permission.SEND_SMS, permission.READ_SMS).
  • Failure messages can include the value under test and the expected result. Contrast this with the assertTrue call above, which lacks a failure message entirely.
Google's fluent assertion library for Java and Android is Truth. We're happy to announce that we've released Truth 1.0, which stabilizes our API after years of fine-tuning.



Truth started in 2011 as a Googler's personal open source project. Later, it was donated back to Google and cultivated by the Java Core Libraries team, the people who bring you Guava.
You might already be familiar with assertion libraries like Hamcrest and AssertJ, which provide similar features. We've designed Truth to have a simpler API and more readable failure messages. For example, here's a failure message from AssertJ:
java.lang.AssertionError:
Expecting:
  <[year: 2019
month: 7
day: 15
]>
to contain exactly in any order:
  <[year: 2019
month: 6
day: 30
]>
elements not found:
  <[year: 2019
month: 6
day: 30
]>
and elements not expected:
  <[year: 2019
month: 7
day: 15
]>
And here's the equivalent message from Truth:
value of:
    iterable.onlyElement()
expected:
    year: 2019
    month: 6
    day: 30

but was:
    year: 2019
    month: 7
    day: 15
For more details, read our comparison of the libraries, and try Truth for yourself.

Also, if you're developing for Android, try AndroidX Test. It includes Truth extensions that make assertions even easier to write and failure messages even clearer:
assertThat(notification).extras().string(EXTRA_BIG_TEXT)
    .isEqualTo("Message has been sent");
assertThat(notification).extras().string(EXTRA_TEXT)
    .contains("Kurt Kluever <[email protected]>");
Coming soon: Kotlin users of Truth can look forward to Kotlin-specific enhancements.
By Chris Povirk, Java Core Libraries

Kotlin Is Everywhere! Join the global event series

Posted by Posted by Florina Muntenescu & Wojtek Kaliciński, Developer Advocates, Android

Last week at Google I/O, we announced a big step: Android development will become increasingly Kotlin-first. It’s a language that many of you already love: over 50% of professional Android developers now use Kotlin, and it’s the fastest-growing language on GitHub. As part of this announcement, many new Jetpack APIs and features will be offered first in Kotlin. So if you’re starting a new project, you should try writing it in Kotlin; code written in Kotlin often means much less code for you–less code to type, test, and maintain.

To help you dive deeper into Kotlin, we’re happy to announce a new program we’re launching together with JetBrains: Kotlin/Everywhere, a series of community-driven events focussing on the potential of Kotlin on all platforms. We are aiming to help learn the essentials and best practices of using Kotlin everywhere, be it for Android, back-end, front-end and other platforms.

Join the Kotlin/Everywhere global event series between June and December 2019.

Who can attend the events?

Whether you are a developer, a speaker, a Kotlin User Group, a Google Developer Group member or any other community leader join us. Anyone interested in learning Kotlin and its ecosystem, sharing knowledge, and hosting a Kotlin-focused event is welcome to attend.

If you are a developer wanting to learn more about Kotlin, or a speaker excited to share your Kotlin experience with others, you can find events near you to join. Just go to the map on the website. More events will be added over time.

How to host your Kotlin/Everywhere event?

If you want to host an event in your city, you can begin by checking out the detailed organizers’ guide. It will help you to decide on the format and what kind of support you might need. All the necessary tips and tricks, materials, and branding assets are inside. Go ahead and submit your event on the official web page.

Besides the detailed organizers’ guide, we also provide you with resources such as content, codelabs, and guidance to help you maximize your success. You can also apply for support: we have speakers from Google/JetBrains and can help by providing funding for venue, food and drinks, swag, or other. We will also list your event on the official website.

Still have questions? Ask them at our hangout sessions for organizers on May 16 and 17.

Let us know if you want to take part! Apply at kotl.in/everywhere

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.

Google I/O 2019: Empowering developers to build the best experiences on Android + Play

Posted by Chet Haase

It's great to be in our backyard again for Google I/O to connect with Android’s developers around the world. The 7,200 attendees at Shoreline Amphitheatre, millions of viewers on the livestream, and thousand of developers at local I/O Extended events across 80+ countries heard about our efforts to make the lives of developers easier. Today at Google I/O, we talked about two big themes; helping our developers become more productive and strengthening user privacy and security in the platform. Let's take a closer look at the major developer news at I/O so far:

Developer Productivity

This year, we focused on a simple idea - we want to save you time every today. By making everything you use even better.

Kotlin

Two years ago, we announced Kotlin was a supported language for Android. Our top developers loved it already, and since then, it’s amazing how fast it’s grown. Over 50% of professional Android developers now use Kotlin, it’s been one of the most-loved languages two years running on Stack Overflow, and one of the fastest-growing on GitHub in number of contributors.

Today we’re announcing another big step: Android development will become increasingly Kotlin-first. Many new Jetpack APIs and features will be offered first in Kotlin. If you’re starting a new project, you should write it in Kotlin; code written in Kotlin often mean much less code for you–less code to type, test, and maintain. And, in partnership with Jetbrains and the Kotlin Foundation, we’re continuing to invest in tooling, docs, trainings and events to make Kotlin even easier to learn and use. This includes Kotlin/Everywhere, a new, global series of events where you can learn more about the language, new Udacity courses, and more.

Android Jetpack

Last year, we announced Android Jetpack, Android’s API to accelerate Android development and make writing high-quality apps easy, with less code. Over 80% of our top 1000 apps are already using Jetpack, as we continue to simplify more every-day developer challenges. Today, we are releasing 6 new Jetpack libraries (in alpha), and bringing 5 libraries to beta quality. Here are 3 highlights:

  • CameraX - You’ve told us working effectively across the range of unique Android devices was tough. CameraX is a new open-source Android Jetpack library to make camera development easier and faster. It provides a consistent camera experience across devices, so you no longer have to maintain device specific configurations. You’ll find support for leading-edge hardware and software features like optical zoom, bokeh, HDR, and night mode on participating manufacturer devices. It works with almost 90% of devices (backwards compatible to L). There’s also an easy migration path from legacy Camera APIs and it works seamlessly with camera2 APIs. 70% of camera usage on Android comes from installed apps (not the device camera app) so we’re really excited to make camera development easier.

  • Architecture Components - We’ve made a number of additions and enhancements based on your feedback. You’ve told us concurrency on Android was hard. So we’re bringing you LiveData and Lifecycles w/ coroutines to support common one-shot asynchronous operations. With the ViewModel with SavedState module, you can eliminate boilerplate code and gain the benefits of using both ViewModel and SavedState with simple APIs to save and retrieve data right from your ViewModel. And in case you missed it, we announced stable releases of WorkManager (background processing) and Navigation (navigation between app screens) just a couple of months ago.
  • Jetpack Compose - Many of you have been asking us for a modern, reactive style UI toolkit for Android, which takes advantage of Kotlin and integrates seamlessly with the platform and all of your existing code. Today, we’re sharing the team’s work on Jetpack Compose. Jetpack Compose is designed to simplify UI development by combining a reactive programming model with the conciseness and ease-of-use of Kotlin. It’s compatible with the existing UI toolkit, so you can mix and match views with direct access to all of the Android and Jetpack APIs. It’s also fully declarative for defining UI components. And, it’s designed with Material, animations, and tools in mind from the start. Starting today we’re developing this in the open, and you can find all the code on AOSP.

Android Studio

Today we’re releasing Android Studio 3.5 to Beta. For months, the team has been exclusively focused on refining and polishing day-to-day development workflows, with Project Marble. Android Studio 3.5 includes better IDE memory management for large projects, lower typing latency, lint improvements, CPU usage optimizations, layout editor improvements, emulator improvements, build changes, as well as a complete rewrite of Instant Run, now called Apply Changes, that now reliably accelerates the ability to see your code changes on a device - plus over 400 high- priority bug fixes.

Machine Learning at Android scale

In Android Q, we’ve made significant improvements to Android’s Neural Networks API (NNAPI). First, we have increased the number of Operators supported from 38 to over 90. The vast majority of models can now be accelerated by NNAPI with no alterations. We’ve also introduced an introspection API for advanced users, allowing full control over which hardware components handle acceleration (e.g. DSP vs. NPU). And, we’ve worked closely with hardware vendors to deliver significant improvements in performance, both in latency and power consumption. Working with MediaTek, we were able to accelerate ML Kit’s face detection API by 9X on the Helio P90. Working with Qualcomm, we were able to accelerate Google’s Lens OCR on the Snapdragon 855’s AI Engine, increasing speed by 3X while also reducing power consumption by 3.7X.

Dynamic features and in-app updates

Last year we introduced the Android App Bundle to help you reduce app size and increase installs. Since then, we’ve seen over 80,000 app bundles in production, with average size savings of 20%. And today we have a number of announcements to help you reduce size and deliver updates to your users even faster. Today we’re glad to share that dynamic feature modules are moving from beta to stable. With dynamic feature modules, you can reduce your app size even more by choosing which parts of your app to deliver - based on conditions like device features, country. You can even deliver modules on-demand, instead of at install time. And today we’re also moving in-app updates from beta to stable. The ability to dynamically update apps is something you’ve been requesting for a long time. Let’s say you have a crucial bug in your app, and you need to push it out right away; you don’t want to wait until users discover an update in the Play Store. Now you can.

User privacy and security in Android Q

As a developer community, we all care about getting this right. It’s about building a platform that offers powerful capabilities for developers, while making sure that user safety and privacy is protected. We introduced Android Q Beta a few months ago with over 50 features and improvements around user privacy and security. These Q changes provide users more transparency and control.

As always, we are working hard to do everything we can for developers adopting the new release. We know you have your own features to build. That’s why, with these Q changes, we’ve worked very hard to minimize the impact for you, as well as to incorporate your feedback. We’ve given as long a notice period as possible, as well as complete and detailed technical information up front, to make it as easy as possible to adopt. We also want to thank the community for your ongoing feedback. It’s been a huge help to the team who are working hard to get this right. A great example are the Beta 3 storage changes, where your feedback helped us evolve the feature over the course of the Betas. Android has a longstanding commitment to minimizing all breaking changes. Our commitment is unchanged, and we’ll work hard to keep Android the open, flexible, and developer friendly platform we all love.

Be a part of Google I/O!

We’ve got a lot of great content in store for you over the next three days, including over 45 sessions across Android. We’re excited for you to join us in-person here at Shoreline, at an I/O Extended event, or online through the livestream. We’re constantly investing in our platform that connects developers to billions of users around the world. To the entire Android community, thank you for your continued support and feedback, and for being a part of Android.

Unfolding right now at #AndroidDevSummit!

Posted by Stephanie Cuthbertson, Director of Product Management

Today, at the Computer History Museum in Mountain View, CA, we kicked off the Android Dev Summit, taking a look back at the last 10 years of Android and then jumping into some important new features for Android developers. Here's a look at some of the things we shared!

Unfolding Android into new experiences

As early as Android 1.6, Android and our partners have contemplated different screen sizes and densities, enabling the platform to power a broad category of form factors and new experiences like Android TV, Android Auto, Wear OS and even Android apps on Chromebooks. Phone screens are an area where Android partners set the bar, introducing "phablets" when phone screens were small. Fast forward to today, when a phablet is... just a phone, a standard size users have come to love.

Now we see a Android device makers creating a new category: Foldables. Taking advantage of new flexible display technology, the screen can literally bend and fold.

There are two variants broadly speaking: two-screen devices and one-screen devices. When folded, foldables look like phones, fitting in your pocket or purse. When unfolded, their defining feature is what we call screen continuity. For example, start a video with the folded smaller screen - and later you can sit down and unfold the device to get a larger tablet-sized screen for a beautiful, immersive experience. As you unfold, the app seamlessly transfers to the bigger screen without missing a beat. We're optimizing Android for this new form factor. And, making changes to help developers everywhere take advantage of the possibilities this creates for amazing new experiences, new ways to engage and delight your users. Tune in to the Foldables session at Dev Summit this week to learn more. Expect to see Foldables coming from several Android manufacturers, including one Samsung previewed today and plans to offer next year.

Kotlin: updates to the fastest growing language

We made Kotlin a first class language on Android in 2017. This month we had over 118,000 new projects using Kotlin started in Android Studio - from those users who opt in to share metrics. That's a 10X increase from last year. It's become the fastest growing language in terms of growth of number of contributors on GitHub, and voted the #2 most loved language on Stack Overflow. In our surveys, the more developers use Kotlin, the higher their satisfaction.

Last week, JetBrains released the latest version of Kotlin, 1.3, which brings new language features, APIs, bug fixes, and performance improvements:

  • Inline classes allow you to create a type which doesn't allocate unless boxed. For the constrained devices that Android apps target, avoiding allocation while retaining type-safety is a big advantage.
  • Unsigned numbers are now part of the Kotlin standard library including UInt, UByte, and ULong. These new types are built using inline classes.
  • Multiplatform code previously written for Android or the JVM can now also target Javascript or native. This unlocks the possibility of reusing parts of your codebase on even more platforms.
  • Coroutines support is now stable. The language and library support combine to simplify how you interact with asynchronous operations and perform concurrent work–things that are essential to every Android app.

All of these new features of Kotlin 1.3 will be integrated into the Kotlin-specific APIs that we provide–a majority of which are through KTX extensions as part of Jetpack.

Android Jetpack: Navigation, Work Manager, and Slices

At Google I/O we announced Jetpack, the next generation of tools and Android APIs to accelerate Android application development. Jetpack builds on the foundations laid out by Support Library and Architecture. Already, 80% of top 1,000 apps and games are using one of the new Jetpack libraries in production.

This summer we moved AndroidX - Jetpack's evolution of the original Android Support Library - to public AOSP. This means you can see features and bug fixes implemented in real-time, and contribute to any of the AndroidX libraries. You can learn more about contributing here.

We've been working to get as much feedback and refinement as possible on two new Architecture Component libraries: Navigation and Work Manager, and we plan to move both to Beta this month. The Navigation Architecture Component offers a simplified way to implement Android's navigation principles in your application, using a single Activity. Plus, the new Navigation Editor in Android Studio creates and edits your navigation architecture. This eliminates navigation boilerplate, gives you atomic navigation operations, easier animated transitions and more. WorkManager makes it easy to perform background tasks in the most efficient manner, choosing the most appropriate solution based on the application state and device API level.

Navigation Editor

We're also excited to see Android Slices move to public Search experiments! At I/O this year we introduced Slices, a new way to bring users to your app. Slices are like a mini snippet of your app, where you can surface content and actions. You can book a flight, play a video, or call a ride. Slices is another example where we want to be open very early, but we want to take the time to get it right. We're moving into public EAP this month with Doist, Kayak and others. We'll run experiments surfacing Slices in Google search results. To learn more, there's also a session today at Dev Summit with more info and best practices.

Android Studio: focusing on productivity, build speed, quality and fundamentals

Android Studio is our official IDE for Android development. We asked where do you spend the most time? When we gather data from Android Studio's opted-in users we see that build time are getting faster with every release, sometimes as fast as 20%, but we also see build time getting slower and slower over time. So, how can both things be true? We've been digging in hard to understand.

It turns out build is a pretty complicated ecosystem. Developer choices makes a huge difference. Our developers are using a very broad (and growing) combination of OSes, custom plug-ins, annotation processors, languages. All of these can significantly affect times. In one case, a plugin some users like to add was silently slowing build speeds by up to 45%. Learning this, we realized we need build profiling and analysis tools so you can easily understand what's slowing your build down. We're also investing more in our own plugins to accelerate performance to make sure we continue to improve the performance of core build.

Android Studio 3.3 launches beta 3 today. In coming releases expect to see a strong focus on quality and fundamentals: reducing the number of crashes and hangs, optimizing memory usage, and fixing user-impacting bugs. We also announced today that we're making Android Studio an officially supported IDE on Chrome OS early next year; learn more here.

Android App Bundles and dynamic features

App sizes have grown dramatically, up 5x since 2012. But larger apps have downsides: lower install conversion rates, lower update rates, and higher uninstalls. This is why we built the Android App Bundle, the new publishing format that serves only the code and resources a user needs to run your app on their specific device; on average apps see 35% size savings compared to a universal APK. The app bundle also saves you time and effort with each release since you don't need to use incomplete solutions like multi-APK. Android Studio 3.2 brought full IDE support of app bundles, and there are now thousands of app bundles in production totaling billions of installs, including Google's apps like YouTube, Google Maps, Google Photos, and Google News.

The app bundle now supports uncompressed native libraries; with no additional developer work needed, the app bundle now makes apps using native libraries an average of 8% smaller to download and 16% smaller on disk on M+ devices.

Once you switch to the app bundle you can also start modularizing your app. With dynamic feature modules, you can load any app functionality on demand instead of at install time. You don't need to keep big features that are only used once, on every single device forever; dynamic features can be installed and uninstalled dynamically when your app requests them.

In-app Updates API

We've heard that you'd like more controls to ensure that users are running the latest and greatest version of your app. To address this, we're launching an In-app Updates API. We're testing the API with early access partners and will be launching it to all developers soon.

You'll have two options with this API; the first is a full-screen experience for critical updates when you expect the user to wait for the update to be applied immediately. The second option is a flexible update, which means the user can keep using the app while the update is downloaded. You can completely customize the update flow so it feels like part of your app.

Instant discovery

We're also making instant apps easier than ever to adopt. We recently made using web URLs optional, enabling you to take your existing play store deep link traffic and send users to your instant experience if it's available. Additionally, we've raised the instant app size limit to 10MB for the Try Now button on the Play Store and web banners to make it even easier to adopt.

In the Android Studio 3.3 beta, you can now build an instant-enabled app bundle. This means that you can now build and deploy both your Instant and installed experiences from a single Android Studio project, and include them in a single Android App Bundle. You only have to upload just ONE artifact for both instant and installed app.

As developers, your feedback has been critical in shaping these investment areas; you are part of how we work, from early ideas, to EAPs and canaries, Beta, and iterating after launch. We hope you join us for the next two days whether you're watching the 30+ sessions on the livestream, joining social, or with us in-person in Mountain View. From the team, a sincere thank you for all your thoughtful feedback and contributions. We hope you enjoy Android Dev Summit.

Kotlin Momentum for Android and Beyond

Posted by James Lau (@jmslau), Product Manager

Today marks the beginning of KotlinConf 2018 - the largest in-person gathering of the Kotlin community annually. 2018 has been a big year for Kotlin, as the language continues to gain adoption and earn the love of developers. In fact, 27% of the top 1000 Android apps on Google Play already use Kotlin. More importantly, Android developers are loving the language with over 97% satisfaction in our most recent survey. It's no surprise that Kotlin was voted as the #2 most-loved language in the 2018 StackOverflow survey.

Google supports Kotlin as a first-class programming language for Android development. In the past 12 months, we have delivered a number of important improvements to the Kotlin developer experience. This includes the Kotlin-friendly SDK, Android KTX, new Lint checks and various Kotlin support improvements in Android Studio. We have also launched Kotlin support in our official documentation, new flagship samples in Kotlin, a new Kotlin Bootcamp Udacity course, #31DaysOfKotlin and other deep dive content. We are committed to continuing to improve the Kotlin developer experience.

As the language continues to advance, more developers are discovering the benefits of Kotlin across the globe. Recently, we traveled to India and worked with local developers like Zomato to better understand how adopting Kotlin has benefited their Android development. Zomato is a leading restaurant search & discovery service that operates in 24 countries, with over 150 million monthly users. Kotlin helped Zomato reduce the number of lines of code in their app significantly, and it has also helped them find important defects in their app at compile time. You can watch their Kotlin adoption story in the video below.

Android Developer Story: Zomato uses Kotlin to write safer, more concise code.

Going beyond Android, we are happy to announce that the Google Cloud Platform team is launching a dedicated Kotlin portal today. This will help developers more easily find resources related to Kotlin on Google Cloud. We want to make it as easy as possible for you to use Kotlin, whether it's on mobile or in the Cloud.

Google Cloud Platform's Kotlin Homepage

Adopting a new language is a major decision for most companies, and you need to be confident that the language you choose will have a bright future. That's why Google has joined forces with JetBrains and established the Kotlin Foundation. The Foundation will ensure that Kotlin continues to advance rapidly, remain free and stay open. You can learn more about the Kotlin Foundation here.

It's an exciting time to be a Kotlin developer. If you haven't tried Kotlin yet, we encourage you to join this growing global community. You can get started by visiting kotlinlang.org or the Android Developer Kotlin page.

Kotlin Momentum for Android and Beyond

Posted by James Lau (@jmslau), Product Manager

Today marks the beginning of KotlinConf 2018 - the largest in-person gathering of the Kotlin community annually. 2018 has been a big year for Kotlin, as the language continues to gain adoption and earn the love of developers. In fact, 27% of the top 1000 Android apps on Google Play already use Kotlin. More importantly, Android developers are loving the language with over 97% satisfaction in our most recent survey. It's no surprise that Kotlin was voted as the #2 most-loved language in the 2018 StackOverflow survey.

Google supports Kotlin as a first-class programming language for Android development. In the past 12 months, we have delivered a number of important improvements to the Kotlin developer experience. This includes the Kotlin-friendly SDK, Android KTX, new Lint checks and various Kotlin support improvements in Android Studio. We have also launched Kotlin support in our official documentation, new flagship samples in Kotlin, a new Kotlin Bootcamp Udacity course, #31DaysOfKotlin and other deep dive content. We are committed to continuing to improve the Kotlin developer experience.

As the language continues to advance, more developers are discovering the benefits of Kotlin across the globe. Recently, we traveled to India and worked with local developers like Zomato to better understand how adopting Kotlin has benefited their Android development. Zomato is a leading restaurant search & discovery service that operates in 24 countries, with over 150 million monthly users. Kotlin helped Zomato reduce the number of lines of code in their app significantly, and it has also helped them find important defects in their app at compile time. You can watch their Kotlin adoption story in the video below.

Android Developer Story: Zomato uses Kotlin to write safer, more concise code.

Going beyond Android, we are happy to announce that the Google Cloud Platform team is launching a dedicated Kotlin portal today. This will help developers more easily find resources related to Kotlin on Google Cloud. We want to make it as easy as possible for you to use Kotlin, whether it's on mobile or in the Cloud.

Google Cloud Platform's Kotlin Homepage

Adopting a new language is a major decision for most companies, and you need to be confident that the language you choose will have a bright future. That's why Google has joined forces with JetBrains and established the Kotlin Foundation. The Foundation will ensure that Kotlin continues to advance rapidly, remain free and stay open. You can learn more about the Kotlin Foundation here.

It's an exciting time to be a Kotlin developer. If you haven't tried Kotlin yet, we encourage you to join this growing global community. You can get started by visiting kotlinlang.org or the Android Developer Kotlin page.

Verifying your Google Assistant media action integrations on Android

Posted by Nevin Mital, Partner Developer Relations

The Media Controller Test (MCT) app is a powerful tool that allows you to test the intricacies of media playback on Android, and it's just gotten even more useful. Media experiences including voice interactions via the Google Assistant on Android phones, cars, TVs, and headphones, are powered by Android MediaSession APIs. This tool will help you verify your integrations. We've now added a new verification testing framework that can be used to help automate your QA testing.

The MCT is meant to be used in conjunction with an app that implements media APIs, such as the Universal Android Music Player. The MCT surfaces information about the media app's MediaController, such as the PlaybackState and Metadata, and can be used to test inter-app media controls.

The Media Action Lifecycle can be complex to follow; even in a simple Play From Search request, there are many intermediate steps (simplified timeline depicted below) where something could go wrong. The MCT can be used to help highlight any inconsistencies in how your music app handles MediaController TransportControl requests.

Timeline of the interaction between the User, the Google Assistant, and the third party Android App for a Play From Search request.

Previously, using the MCT required a lot of manual interaction and monitoring. The new verification testing framework offers one-click tests that you can run to ensure that your media app responds correctly to a playback request.

Running a verification test

To access the new verification tests in the MCT, click the Test button next to your desired media app.

MCT Screenshot of launch screen; contains a list of installed media apps, with an option to go to either the Control or Test view for each.

The next screen shows you detailed information about the MediaController, for example the PlaybackState, Metadata, and Queue. There are two buttons on the toolbar in the top right: the button on the left toggles between parsable and formatted logs, and the button on the right refreshes this view to display the most current information.

MCT Screenshot of the left screen in the Testing view for UAMP; contains information about the Media Controller's Playback State, Metadata, Repeat Mode, Shuffle Mode, and Queue.

By swiping to the left, you arrive at the verification tests view, where you can see a scrollable list of defined tests, a text field to enter a query for tests that require one, and a section to display the results of the test.

MCT Screenshot of the right screen in the Testing view for UAMP; contains a list of tests, a query text field, and a results display section.

As an example, to run the Play From Search Test, you can enter a search query into the text field then hit the Run Test button. Looks like the test succeeded!

MCT Screenshot of the right screen in the Testing view for UAMP; the Play From Search test was run with the query 'Memories' and ended successfully.

Below are examples of the Pause Test (left) and Seek To test (right).

MCT Screenshot of the right screen in the Testing view for UAMP; a Pause test was run successfully. MCT Screenshot of the right screen in the Testing view for UAMP; a Seek To test was run successfully.

Android TV

The MCT now also works on Android TV! For your media app to work with the Android TV version of the MCT, your media app must have a MediaBrowserService implementation. Please see here for more details on how to do this.

On launching the MCT on Android TV, you will see a list of installed media apps. Note that an app will only appear in this list if it implements the MediaBrowserService.

Android TV MCT Screenshot of the launch screen; contains a list of installed media apps that implement the MediaBrowserService.

Selecting an app will take you to the testing screen, which will display a list of verification tests on the right.

Android TV MCT Screenshot of the testing screen; contains a list of tests on the right side.

Running a test will populate the left side of the screen with selected MediaController information. For more details, please check the MCT logs in Logcat.

Android TV MCT Screenshot of the testing screen; the Pause test was run successfully and the left side of the screen now displays selected MediaController information.

Tests that require a query are marked with a keyboard icon. Clicking on one of these tests will open an input field for the query. Upon hitting Enter, the test will run.

Android TV MCT Screenshot of the testing screen; clicking on the Seek To test opened an input field for the query.

To make text input easier, you can also use the ADB command:

adb shell input text [query]

Note that '%s' will add a space between words. For example, the command adb shell input text hello%sworld will add the text "hello world" to the input field.

What's next

The MCT currently includes simple single-media-action tests for the following requests:

  • Play
  • Play From Search
  • Play From Media ID
  • Play From URI
  • Pause
  • Stop
  • Skip To Next
  • Skip To Previous
  • Skip To Queue Item
  • Seek To

For a technical deep dive on how the tests are structured and how to add more tests, visit the MCT GitHub Wiki. We'd love for you to submit pull requests with more tests that you think are useful to have and for any bug fixes. Please make sure to review the contributions process for more information.

Check out the latest updates on GitHub!

Android Pie SDK is now more Kotlin-friendly

Posted by James Lau, Product Manager (@jmslau)

When using the Java programming language, one of the most common pitfalls is trying to access a member of a null reference, causing a NullPointerException to be thrown. Kotlin offers protection against this by baking nullable and non-nullable types into the type system. This helps eliminate NullPointerExceptions from your code and improve your app's overall quality. When Kotlin code is calling into APIs written in the Java programming language, it relies on nullability annotations in those APIs to determine the nullability of each parameter and the return type. Unannotated parameters and return types are treated as platform types, which weakens the null-safety guarantee of Kotlin.

As part of yesterday's Android 9 announcement, we have also released a new Android SDK that contains nullability annotations for some of the most frequently used APIs. This will preserve the null-safety guarantee when your Kotlin code is calling into any annotated APIs in the SDK. Even if you are using the Java programming language, you can still benefit from these annotations by using Android Studio to catch nullability contract violations.

Not a breaking change

Normally, nullability contract violations in Kotlin result in compilation errors. But to ensure the newly annotated APIs are compatible with your existing code, we are using an internal mechanism provided by the Kotlin compiler team to mark the APIs as recently annotated. Recently annotated APIs will result only in warnings instead of errors from the Kotlin compiler. You will need to use Kotlin 1.2.60 or later.

Our plan is to have newly added nullability annotations produce warnings only, and increase the severity level to errors starting in the following year's Android SDK. The goal is to provide you with sufficient time to update your code.

How to use the "Kotlin-friendly" SDK

To get started, go to Tools > SDK Manager in Android Studio. Select Android SDK on the left menu, and make sure the SDK Platforms tab is open.

Use SDK Manager in Android Studio to install SDK for API Level 28 Revision 6

Check Android 8.+ (P) and click OK. This will install the Android SDK Platform 28 revision 6 if it is not already installed. After that, set your project's compile SDK version to API 28 to start using the new Android Pie SDK with nullability annotations.

Use the Project Structure Dialog to change your project's Compile Sdk Version to API 28

You may also need to update your Kotlin plugin in Android Studio if it's not already up-to-date. Make sure your Kotlin plugin version is 1.2.60 or later by going to Tools > Kotlin > Configure Kotlin Plugin Updates.

Once it's set up, your builds will start showing warnings if you have any code that violates nullability contracts in the Android SDK. An example of such a warning is shown below.

Sample warning from the Kotlin compiler when code violates a recently added nullability contract in the Android SDK.

You will also start seeing warnings in Android Studio's code editor if you call an Android API with the incorrect nullability. An example is shown below.

Android Studio warning about passing a null reference to a parameter annotated as a recently non-null type in the android.graphics.Path API.

Leveraging nullability annotations from the Java programming language

You can benefit from the new nullability annotations even if your code is in the Java programming language. By default, Android Studio will highlight any nullability contract violations with a warning, like the one below:

Android Studio showing a warning about nullability contract violation in code written in the Java programming language

To ensure that you have this inspection enabled, you can go to the IDE's settings page and search for "Constant conditions & exceptions" inspection and make sure that item is checked.

Use the Inspections page under Settings to ensure the Constant conditions & exceptions code inspection is enabled.

If you are using the Java programming language, nullability contract violations will not produce any compiler warning or error. Only the in-IDE code inspections are available to flag these issues.

You can also run code inspections across your entire project and see the aggregated results. Click on Analyze > Inspect Code… to start.

What's Next

The Android SDK API surface is very large, and we have only annotated a small percentage of the APIs so far - there is still lots of work remaining. Over the next several Android SDK releases, we will continue to add nullability annotations to the existing Android APIs, as well as making sure new APIs are annotated.

With the "Kotlin-friendly" Android SDK, the nullability annotations in AndroidX (part of the Jetpack family), and Android KTX, we are continuing to improve the Android APIs for developers using Kotlin. If you have not yet tried Kotlin, we encourage you to try it. Not only can Kotlin make your code more concise, it can also improve the stability of your apps.

Happy Kotlin-ing!

A New Universal Music Player

Posted by Nicole Borrelli, Android Developer, Programs Engineer


Screenshot of UAMP v2's UI showing a pair of albums

The Universal Android Music Player (or "UAMP") is a favorite on GitHub for music app developers with over 9,500 stars and 3,000 forks. Since UAMP was first released, Android development has changed significantly. ExoPlayer has improved, Architecture Components were introduced, and Kotlin became a first-class language for Android developers.

We decided that the best way to integrate the modern features for our beloved music app would be to re-write UAMP.

UAMP v2 was built from the ground up in Kotlin. The UI is built around ViewModels and LiveData. Playback, and particularly integration with MediaSessionCompat, was vastly simplified by utilizing the MediaSession extension of ExoPlayer.

We also added a bunch of new songs by The Kyoto Connection and Kai Engel.

There are some features from UAMP v1 that haven't been integrated into the new code yet. The missing features include Android TV with the Leanback library and remote playback via Google Cast. Even though these features aren't yet included in v2, we wanted to show you the new updates as soon as possible. The old code will continue to be available in the v1 branch on GitHub, so please take a look there to see how to use those features in a music app.

We would love your feedback on which features to add next. We are considering offline playback, improving the integration with Android Auto, and using the upcoming Navigation components of Jetpack for the UI. We'll be creating GitHub issues for features and improvements to help you let us know what is most important to you. Go vote on these features to let us know where we should focus our efforts.

We'd also like to invite you to open pull requests for bug fixes and features that are missing. See the contributions process for more information.

Grab the code from GitHub!