Tag Archives: #11WeeksOfAndroid

11 Weeks of Android: Android Developer Tools

Posted by Jamal Eason, Product Manager, Android

11 Weeks of Android, Week 7 with badge

This blog post is part of a weekly series for #11WeeksOfAndroid. For each of the #11WeeksOfAndroid, we’re diving into a key area so you don’t miss anything. This week, we spotlighted Android Developer Tools; here’s a look at what you should know.

The big news

During the 11 weeks of Android, we launched a range of developer tool updates in Android Studio. As of today, you can find version 4.0 of Android Studio on the stable release channel, version 4.1 on the beta channel, and the very latest features of version 4.2 on the canary channel. The focus across each of these versions is a balance of app productivity and delivery of a high quality product that you can rely on for app development. For each day of this past week we highlighted improvements and tips in the key points of your development flow from app design, coding, deployment, build, app testing with the emulator, to app performance profiling. This blog highlights the content that we released during the Android Developer Tools week of 11 Weeks of Android.

What to watch and read

To see an overview of what is new in Android Developer Tools across the recent releases of Android Studio, check out this video from the #Android11 Beta launch which includes an exciting and in-depth demo.

What’s New in Android Development Tools

Design

At the beginning of the week we had a day of content focused on app design tools for developers. To start, watch this overview video of the latest updates in design tools:

What’s new in Design Tools

We also posted two in-depth blog posts for the design tools day:

  • Introducing the Motion Editor - provides a quick tour of the new Motion Editor and how to use the latest features to create animations for your app.

To debug your layouts, watch our video on the updates to the layout inspector:

Debugging UI issues with Layout Inspector

And lastly for design tools, we released a video about the latest developments for Jetpack Compose Design tools:

What's new in Compose Design Tools

Coding & Deployment

During the week, we posted tips and tricks to improve your coding experience and app deployment flow in Android Studio. Check out the following social media channels to review the latest postings:

  • @androidstudio - the Twitter channel for the official IDE for Android app development.
  • @androiddev - delivers news and announcements for developers from the Android team at Google

We also shared a new video on how to use the new database inspector in Android Studio:

Database Inspector

Additionally, you will find an updated blog on the development tools we have in place for Jetpack Hilt:

Build

In the middle of the week, we released four blogs posts around the build system in Android developer tools, which included:

  • Configuration Caching deep dive - a technical explanation on this new preview feature from Gradle and how to try it out in your project to speed up your builds.
  • Shrinking Your App with R8 - provides an overview of the features available in R8, the reduction in code size you might expect, and show how to enable these features in R8.

Android Emulator

On top of sharing a series of best practices and tips on social media about using the Android Emulator during the week, you can also a full summary in the following in-depth article:

Performance Profilers

We know improving app performance is critical for a great user experience. Therefore, we ended the week with a day on performance profilers content. To start, we posted a video about System Trace and how you can use it to troubleshoot app performance issues:

Troubleshooting app performance issues with System Trace in Android Studio

Plus, we published a blog post on C++ memory profiling:

Learning path

If you’re looking for an easy way to pick up the highlights of this week, check out the Developer Tools pathway. A pathway is an ordered tutorial that allows users to complete a pre-defined module that culminates in a quiz. It includes videos and blog posts. A virtual badge is awarded to each user who passes the quiz. Test your knowledge of key takeaways about Developer Tools to earn a limited edition badge.

Key takeaways

Thank you for tuning in and learning about the latest in Android Development tools. Thanks to all of you who chatted with us during the Reddit AMA this week. Throughout this past week, we showcased features that can be found either in the latest stable release or the canary release channel of Android Studio. If you want to try out what you learned this week, download Android Studio today.

Below, you will find a quick listing of where you will find each of the major features. Note, that features in non-stable versions may not land in a particular version until they have reached our quality bar:

Features found in Android Studio 4.0 (Stable Channel)

  • Motion Editor
  • Layout Inspector
  • Layout Validation
  • Custom View Preview
  • CPU Profiler Update
  • R8 Rules Editing
  • Build Analyzer
  • Dynamic Feature Dependency
  • Clangd support
  • Intellij 2019.3

Features found in Android Studio 4.1 (Beta Channel)

  • Database Inspector
  • Dependency Injection Tools
  • Faster Apply Changes
  • Gradle Configuration Caching (Preview)
  • Custom View Preview
  • Android Emulator in IDE
  • Instrumentation Testing
  • Profiler UI Updates
  • Native Memory Profiling
  • System Trace 2.0
  • New Gradle API
  • MLKit & TFLite Model Import
  • Intellij 2020.1

Features found in Android Studio 4.2 + (Canary Channel)

  • Compose Interactive Preview
  • Compose Animation Visualization
  • Compose Deploy to Device
  • Sample Data API for Compose
  • Compose Editing Support
  • Test Failure Retention
  • Android Emulator- 5G Connectivity and Foldable Support
  • Intellij 2020.2 - coming soon

Resources

You can find the entire playlist of #11WeeksOfAndroid video content here, and learn more about each week here. We’ll continue to spotlight new areas each week, so keep an eye out and follow us on Twitter and YouTube. Thanks so much for letting us be a part of this experience with you!

11 Weeks of Android: Android Developer Tools

Posted by Jamal Eason, Product Manager, Android

11 Weeks of Android, Week 7 with badge

This blog post is part of a weekly series for #11WeeksOfAndroid. For each of the #11WeeksOfAndroid, we’re diving into a key area so you don’t miss anything. This week, we spotlighted Android Developer Tools; here’s a look at what you should know.

The big news

During the 11 weeks of Android, we launched a range of developer tool updates in Android Studio. As of today, you can find version 4.0 of Android Studio on the stable release channel, version 4.1 on the beta channel, and the very latest features of version 4.2 on the canary channel. The focus across each of these versions is a balance of app productivity and delivery of a high quality product that you can rely on for app development. For each day of this past week we highlighted improvements and tips in the key points of your development flow from app design, coding, deployment, build, app testing with the emulator, to app performance profiling. This blog highlights the content that we released during the Android Developer Tools week of 11 Weeks of Android.

What to watch and read

To see an overview of what is new in Android Developer Tools across the recent releases of Android Studio, check out this video from the #Android11 Beta launch which includes an exciting and in-depth demo.

What’s New in Android Development Tools

Design

At the beginning of the week we had a day of content focused on app design tools for developers. To start, watch this overview video of the latest updates in design tools:

What’s new in Design Tools

We also posted two in-depth blog posts for the design tools day:

  • Introducing the Motion Editor - provides a quick tour of the new Motion Editor and how to use the latest features to create animations for your app.

To debug your layouts, watch our video on the updates to the layout inspector:

Debugging UI issues with Layout Inspector

And lastly for design tools, we released a video about the latest developments for Jetpack Compose Design tools:

What's new in Compose Design Tools

Coding & Deployment

During the week, we posted tips and tricks to improve your coding experience and app deployment flow in Android Studio. Check out the following social media channels to review the latest postings:

  • @androidstudio - the Twitter channel for the official IDE for Android app development.
  • @androiddev - delivers news and announcements for developers from the Android team at Google

We also shared a new video on how to use the new database inspector in Android Studio:

Database Inspector

Additionally, you will find an updated blog on the development tools we have in place for Jetpack Hilt:

Build

In the middle of the week, we released four blogs posts around the build system in Android developer tools, which included:

  • Configuration Caching deep dive - a technical explanation on this new preview feature from Gradle and how to try it out in your project to speed up your builds.
  • Shrinking Your App with R8 - provides an overview of the features available in R8, the reduction in code size you might expect, and show how to enable these features in R8.

Android Emulator

On top of sharing a series of best practices and tips on social media about using the Android Emulator during the week, you can also a full summary in the following in-depth article:

Performance Profilers

We know improving app performance is critical for a great user experience. Therefore, we ended the week with a day on performance profilers content. To start, we posted a video about System Trace and how you can use it to troubleshoot app performance issues:

Troubleshooting app performance issues with System Trace in Android Studio

Plus, we published a blog post on C++ memory profiling:

Learning path

If you’re looking for an easy way to pick up the highlights of this week, check out the Developer Tools pathway. A pathway is an ordered tutorial that allows users to complete a pre-defined module that culminates in a quiz. It includes videos and blog posts. A virtual badge is awarded to each user who passes the quiz. Test your knowledge of key takeaways about Developer Tools to earn a limited edition badge.

Key takeaways

Thank you for tuning in and learning about the latest in Android Development tools. Thanks to all of you who chatted with us during the Reddit AMA this week. Throughout this past week, we showcased features that can be found either in the latest stable release or the canary release channel of Android Studio. If you want to try out what you learned this week, download Android Studio today.

Below, you will find a quick listing of where you will find each of the major features. Note, that features in non-stable versions may not land in a particular version until they have reached our quality bar:

Features found in Android Studio 4.0 (Stable Channel)

  • Motion Editor
  • Layout Inspector
  • Layout Validation
  • Custom View Preview
  • CPU Profiler Update
  • R8 Rules Editing
  • Build Analyzer
  • Dynamic Feature Dependency
  • Clangd support
  • Intellij 2019.3

Features found in Android Studio 4.1 (Beta Channel)

  • Database Inspector
  • Dependency Injection Tools
  • Faster Apply Changes
  • Gradle Configuration Caching (Preview)
  • Custom View Preview
  • Android Emulator in IDE
  • Instrumentation Testing
  • Profiler UI Updates
  • Native Memory Profiling
  • System Trace 2.0
  • New Gradle API
  • MLKit & TFLite Model Import
  • Intellij 2020.1

Features found in Android Studio 4.2 + (Canary Channel)

  • Compose Interactive Preview
  • Compose Animation Visualization
  • Compose Deploy to Device
  • Sample Data API for Compose
  • Compose Editing Support
  • Test Failure Retention
  • Android Emulator- 5G Connectivity and Foldable Support
  • Intellij 2020.2 - coming soon

Resources

You can find the entire playlist of #11WeeksOfAndroid video content here, and learn more about each week here. We’ll continue to spotlight new areas each week, so keep an eye out and follow us on Twitter and YouTube. Thanks so much for letting us be a part of this experience with you!

Introducing the Motion Editor

Posted by Scott Swarthout, Product Manager

We spoke with the Android developer community and learned that animations are important for making UIs more intuitive and memorable. However, we also heard that adding complex animation to Android apps has been a difficult task.To address this problem, we created a powerful set of APIs with Motion Layout and a corresponding tool – Motion Editor, that when combined make it easier to build pixel-perfect animations. This blog is a quick tour of the new Motion Editor and how to use the latest features during your animation development. Additionally today, you can now watch a new video series specifically created to teach you about the various APIs included with MotionLayout. Watch here.

Motion Editor is a visual design editor for the MotionLayout layout type, making it easier to create and preview animations. We just released the stable version Motion Editor in Android Studio 4.0 and we already see many developers using it to build animations.

Animation running in the Motion Editor

The Motion Editor is an extension of Android Studio’s layout editor, and automatically opens when you select the Design or Split view on an XML file containing a MotionLayout. From there, you can edit your layout and Motion Scene files using the familiar interactive tools of the Layout Editor as well as preview your animations right from the Android Studio preview pane.

Motion Editor

The Motion Editor is broken up into several panels which we will describe in this article. The main panels are: Overview, Selection, Attribute, and Preview.

The Motion Editor has four main panels


Overview panel

MotionLayout helps you animate layout changes, which you specify as transitions between ConstraintSets. The Motion Editor helps you visualize these states with the Overview panel. To edit constraints in a ConstraintSet, click on the corresponding box in the Overview panel.

MotionLayout Scene with two ConstraintSets, start and end, and a Transition between them


Selection panel

The Selection panel provides detailed controls based on the state of the Overview panel. It has three modes:

  1. Motion Layout selected
  2. ConstraintSet selected
  3. Transition selected

The selection panel has three modes depending on the state of the Overview panel

MotionLayout selected

The Motion Editor supports editing of the base Motion Layout. When Motion Layout is selected in the Overview panel, you can select components to see if they are properly constrained.

Check if components are properly constrained with the Selection panel

ConstraintSet selected

When a ConstraintSet is selected, the Selection panel displays the list of components and a checkmark to indicate if the component is constrained in this ConstraintSet.

Select components to be included in the ConstraintSet


Transition selected

When a transition is selected, you can control the playback of the animation with the animation toolbar. When an animation is selected, click Play ▶️ above the timeline to preview the animation.

Preview animations on the Motion Editor timeline

Keyframes

Sometimes you want to modify the path a view takes during an animation. To do this, MotionLayout uses keyframes. We build keyframe editing into the editor to make it easy to tweak animations. To create a new keyframe, click on the new keyframe icon in the top right of the selection panel. This action opens a dialog where you can set attributes for the keyframe. To edit a keyframe, click on the diamond ◆ icon to open the KeyFrame attribute panel.

Create keyframes with the selection panel


Attribute panel

Creating animations in MotionLayout involves editing lots of view parameters, so we brought the Attribute panel from the Layout Editor into the Motion Editor. The Attribute panel includes handy visualizations for Constraints as well as all the attributes set on each view in the Motion Scene file.

Constraint visualization in the Attribute panel

The Attribute panel is also where you can create custom attributes. You use custom attributes when you want to animate view properties that are not part of the ConstraintLayout or MotionLayout APIs, such as backgroundColor. We made it easy to create custom attributes with autocomplete and input validation for all view properties.

Preview panel

We wanted to make it easy to quickly edit and get immediate feedback when working on animations, so you can view animations right from the Preview panel. Now you don’t have to recompile and redeploy your app every time you want to make a small tweak to your animation.

We also added a number of features to the Preview panel to make it easier to understand how views are animating. You can preview animations with the Design view and Blueprint view to get a clearer idea of how your views are moving with fewer visual distractions.



We also added visualizations for the paths views take across the screen, including markers for keyframes. We hope these features make it easier to parse complex transitions and simplify the creation experience.



The Motion Editor is available in Android Studio 4.0, give it a try and let us know what you think! We are eager to see what the community builds with MotionLayout and the Motion Editor. The Android Studio team is constantly gathering feedback to improve the experience of using our tools, so if you have any ideas for new features or run into any issues using these tools, please file a bug.

The code used in this example, along with several other MotionLayout examples, are available on our GitHub sample page, found here.

For more information on MotionLayout, see the following links:

Introducing the Motion Editor

Posted by Scott Swarthout, Product Manager

We spoke with the Android developer community and learned that animations are important for making UIs more intuitive and memorable. However, we also heard that adding complex animation to Android apps has been a difficult task.To address this problem, we created a powerful set of APIs with Motion Layout and a corresponding tool – Motion Editor, that when combined make it easier to build pixel-perfect animations. This blog is a quick tour of the new Motion Editor and how to use the latest features during your animation development. Additionally today, you can now watch a new video series specifically created to teach you about the various APIs included with MotionLayout. Watch here.

Motion Editor is a visual design editor for the MotionLayout layout type, making it easier to create and preview animations. We just released the stable version Motion Editor in Android Studio 4.0 and we already see many developers using it to build animations.

Animation running in the Motion Editor

The Motion Editor is an extension of Android Studio’s layout editor, and automatically opens when you select the Design or Split view on an XML file containing a MotionLayout. From there, you can edit your layout and Motion Scene files using the familiar interactive tools of the Layout Editor as well as preview your animations right from the Android Studio preview pane.

Motion Editor

The Motion Editor is broken up into several panels which we will describe in this article. The main panels are: Overview, Selection, Attribute, and Preview.

The Motion Editor has four main panels


Overview panel

MotionLayout helps you animate layout changes, which you specify as transitions between ConstraintSets. The Motion Editor helps you visualize these states with the Overview panel. To edit constraints in a ConstraintSet, click on the corresponding box in the Overview panel.

MotionLayout Scene with two ConstraintSets, start and end, and a Transition between them


Selection panel

The Selection panel provides detailed controls based on the state of the Overview panel. It has three modes:

  1. Motion Layout selected
  2. ConstraintSet selected
  3. Transition selected

The selection panel has three modes depending on the state of the Overview panel

MotionLayout selected

The Motion Editor supports editing of the base Motion Layout. When Motion Layout is selected in the Overview panel, you can select components to see if they are properly constrained.

Check if components are properly constrained with the Selection panel

ConstraintSet selected

When a ConstraintSet is selected, the Selection panel displays the list of components and a checkmark to indicate if the component is constrained in this ConstraintSet.

Select components to be included in the ConstraintSet


Transition selected

When a transition is selected, you can control the playback of the animation with the animation toolbar. When an animation is selected, click Play ▶️ above the timeline to preview the animation.

Preview animations on the Motion Editor timeline

Keyframes

Sometimes you want to modify the path a view takes during an animation. To do this, MotionLayout uses keyframes. We build keyframe editing into the editor to make it easy to tweak animations. To create a new keyframe, click on the new keyframe icon in the top right of the selection panel. This action opens a dialog where you can set attributes for the keyframe. To edit a keyframe, click on the diamond ◆ icon to open the KeyFrame attribute panel.

Create keyframes with the selection panel


Attribute panel

Creating animations in MotionLayout involves editing lots of view parameters, so we brought the Attribute panel from the Layout Editor into the Motion Editor. The Attribute panel includes handy visualizations for Constraints as well as all the attributes set on each view in the Motion Scene file.

Constraint visualization in the Attribute panel

The Attribute panel is also where you can create custom attributes. You use custom attributes when you want to animate view properties that are not part of the ConstraintLayout or MotionLayout APIs, such as backgroundColor. We made it easy to create custom attributes with autocomplete and input validation for all view properties.

Preview panel

We wanted to make it easy to quickly edit and get immediate feedback when working on animations, so you can view animations right from the Preview panel. Now you don’t have to recompile and redeploy your app every time you want to make a small tweak to your animation.

We also added a number of features to the Preview panel to make it easier to understand how views are animating. You can preview animations with the Design view and Blueprint view to get a clearer idea of how your views are moving with fewer visual distractions.



We also added visualizations for the paths views take across the screen, including markers for keyframes. We hope these features make it easier to parse complex transitions and simplify the creation experience.



The Motion Editor is available in Android Studio 4.0, give it a try and let us know what you think! We are eager to see what the community builds with MotionLayout and the Motion Editor. The Android Studio team is constantly gathering feedback to improve the experience of using our tools, so if you have any ideas for new features or run into any issues using these tools, please file a bug.

The code used in this example, along with several other MotionLayout examples, are available on our GitHub sample page, found here.

For more information on MotionLayout, see the following links:

11 Weeks of Android: Jetpack

Posted by Diana Wong, Product Manager, Android Jetpack

Android Jetpack Week 6 banner

This blog post is part of a weekly series for #11WeeksOfAndroid. For each of the #11WeeksOfAndroid, we’re diving into a key area so you don’t miss anything.This week, we spotlighted Jetpack; here’s a look at what you should know.

The big news

In 2018, we launched Android Jetpack as a suite of libraries to help developers follow best practices, reduce boilerplate code, and write code that works consistently across Android versions and devices. We are excited about the growth we’ve seen and the incredible feedback that developers like you have shared with us. 47% of the top 1000 apps use 2 or more Jetpack libraries, not including core libraries like AppCompat or Lifecycle. Our work over the past year has been about making the basics easy for Android developers, so that you can focus on the code you care about. We have released many updates to our existing libraries as well as new libraries to help make building high-quality apps easier.

What to watch

We have also been busy pushing out many updates over the past year!

For an overall look at what’s new in Jetpack, be sure to check out our talk from #Android11 Beta launch:

It’s a quick fly-by introducing many of the updates to our libraries, with pointers on how to get started.

This week, we’ve also done deep dives into major releases like Hilt, including cheat sheets to help you get started, and how we migrated our own samples to use Hilt for dependency injection. Less boilerplate = more fun.

Paging 3.0 is one of our first libraries written Kotlin-first and based on coroutines. The Paging library adds the features you asked for like better error handling, easier list transformations like map or filter, and support for common features like list separators, headers, and footers. We added RxJava, LiveData and ListenableFutures support and backwards compatibility with Paging 2, so it’s easier to migrate.

Using the Camera in your app? CameraX is in Beta and helps developers manage edge cases across different devices and OS versions, so that you don’t have to.

This year, we've made several major improvements with the release of Navigation 2.3, which allows you to navigate between different screens of your app with ease while also allowing you to follow Android UI principles. Let us navigate you through them all here:

Spotlight on Permissions

In Android 11, we continued our work to give users even more control over sensitive permissions. At the same time, it's very important to us that we make it as easy as possible for you as developers to build for Android. With the changes in privacy over the past several releases, Android Jetpack is making it easier for your app to work with Permissions. Now there are type-safe contracts for common intents and more via new ActivityResult APIs. These changes simplify how you request permissions, and we’ll continue to work on making permissions easier in the future. Find out more in this post.

Learning path

Take a look at our new Learning pathway for an easy way to go through all the highlights from this week. It’s an ordered tutorial which guides you through our new content, culminating in a quiz. Bonus: You earn a bright and shiny Jetpack badge to be saved to your Google Developer Profile. In addition to the learning pathway, we’ve also got a new library explorer to make it simple to find more about Jetpack libraries you might be looking for and their latest updates.

Key takeaways

Best practices are baked into Jetpack libraries, giving opinionated guidance to make it easier for you to build a higher-quality Android app. We’ve released new features to Navigation and Workmanager, updates to increase the stability of CameraX, added robustness for Biometrics, and more. We’ve also launched new libraries, like our collaboration with Dagger for Hilt and a new library to help improve app startup. Your feedback is important to us; so give these libraries a shot, tell us what you think, and help us improve them!

Resources

You can find the entire playlist of #11WeeksOfAndroid video content here, and learn more about each week here. We’ll continue to spotlight new areas each week, so keep an eye out and follow us on Twitter and YouTube. Thanks so much for letting us be a part of this experience with you!

Improving inter-activity communication with Jetpack ActivityResult

Posted by Yacine Rezgui, Developer Advocate

Whether you're requesting a permission, selecting a file from the system file manager, or expecting data from a 3rd party app, passing data between activities is a core element in inter-process communication on Android. We’ve recently released the new ActivityResult APIs to help handle these activity results.

Previously, to get results from started activities, apps needed to implement an onActivityResult() method in their activities and fragments, check which requestCode a result is referring to, verify that the requestCode is OK, and finally inspect its result data or extended data.

This leads to complicated code, and it doesn’t provide a type-safe interface for expected arguments when sending or receiving data from an activity.

What are the ActivityResult APIs?

The ActivityResult APIs were added to the Jetpack activity and fragment libraries, making it easier to get results from activities by providing type-safe contracts. These contracts define expected input and result types for common actions like taking a picture or requesting a permission, while also providing a way to create your own contracts.

The ActivityResult APIs provide components for registering for an activity result, launching a request, and handling its result once it is returned by the system. You can also receive the activity result in a separate class from where the activity is launched and still rely on the type-safe contracts.

How to use it

To demonstrate how to use the ActivityResult APIs, let’s go over an example where we’re opening a document.

First, you need to add the following dependencies to your gradle file:

repositories {
    google()
    maven()
}

dependencies {
  implementation "androidx.activity:activity:1.2.0-alpha02"
  implementation "androidx.activity:fragment:1.3.0-alpha02"
}

You need to register a callback along with the contract that defines its input and output types.

In this context, GetContent() refers to the ACTION_GET_DOCUMENT intent, and is one of the default contracts already defined in the Activity library. You can find the complete list of contracts here.

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
    // Handle the returned Uri
}

Now we need to launch our activity using the returned launcher. As you can set a mime type filter when listing the selectable files, GetContent.launch() will accept a string as a parameter:

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
    // Handle the returned Uri
}

override fun onCreate(savedInstanceState: Bundle?) {
    // ...

    val selectButton = findViewById<Button>(R.id.select_button)

    selectButton.setOnClickListener {
        // Pass in the mime type you'd like to allow the user to select
        // as the input
        getContent.launch("image/*")
    }
}

Once an image has been selected and you return to your activity, your registered callback will be executed with the expected results. As you saw through the code snippets, ActivityResult brings an easier developer experience when dealing with results from activities.

Start using Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02 for a type-safe way to handle your intent results with the new ActivityResult APIs.

Let us know what you think and how we can make it better by providing feedback on the issue tracker.

Improving inter-activity communication with Jetpack ActivityResult

Posted by Yacine Rezgui, Developer Advocate

Whether you're requesting a permission, selecting a file from the system file manager, or expecting data from a 3rd party app, passing data between activities is a core element in inter-process communication on Android. We’ve recently released the new ActivityResult APIs to help handle these activity results.

Previously, to get results from started activities, apps needed to implement an onActivityResult() method in their activities and fragments, check which requestCode a result is referring to, verify that the requestCode is OK, and finally inspect its result data or extended data.

This leads to complicated code, and it doesn’t provide a type-safe interface for expected arguments when sending or receiving data from an activity.

What are the ActivityResult APIs?

The ActivityResult APIs were added to the Jetpack activity and fragment libraries, making it easier to get results from activities by providing type-safe contracts. These contracts define expected input and result types for common actions like taking a picture or requesting a permission, while also providing a way to create your own contracts.

The ActivityResult APIs provide components for registering for an activity result, launching a request, and handling its result once it is returned by the system. You can also receive the activity result in a separate class from where the activity is launched and still rely on the type-safe contracts.

How to use it

To demonstrate how to use the ActivityResult APIs, let’s go over an example where we’re opening a document.

First, you need to add the following dependencies to your gradle file:

repositories {
    google()
    maven()
}

dependencies {
  implementation "androidx.activity:activity:1.2.0-alpha02"
  implementation "androidx.activity:fragment:1.3.0-alpha02"
}

You need to register a callback along with the contract that defines its input and output types.

In this context, GetContent() refers to the ACTION_GET_DOCUMENT intent, and is one of the default contracts already defined in the Activity library. You can find the complete list of contracts here.

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
    // Handle the returned Uri
}

Now we need to launch our activity using the returned launcher. As you can set a mime type filter when listing the selectable files, GetContent.launch() will accept a string as a parameter:

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
    // Handle the returned Uri
}

override fun onCreate(savedInstanceState: Bundle?) {
    // ...

    val selectButton = findViewById<Button>(R.id.select_button)

    selectButton.setOnClickListener {
        // Pass in the mime type you'd like to allow the user to select
        // as the input
        getContent.launch("image/*")
    }
}

Once an image has been selected and you return to your activity, your registered callback will be executed with the expected results. As you saw through the code snippets, ActivityResult brings an easier developer experience when dealing with results from activities.

Start using Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02 for a type-safe way to handle your intent results with the new ActivityResult APIs.

Let us know what you think and how we can make it better by providing feedback on the issue tracker.

Improving inter-activity communication with Jetpack ActivityResult

Posted by Yacine Rezgui, Developer Advocate

Whether you're requesting a permission, selecting a file from the system file manager, or expecting data from a 3rd party app, passing data between activities is a core element in inter-process communication on Android. We’ve recently released the new ActivityResult APIs to help handle these activity results.

Previously, to get results from started activities, apps needed to implement an onActivityResult() method in their activities and fragments, check which requestCode a result is referring to, verify that the requestCode is OK, and finally inspect its result data or extended data.

This leads to complicated code, and it doesn’t provide a type-safe interface for expected arguments when sending or receiving data from an activity.

What are the ActivityResult APIs?

The ActivityResult APIs were added to the Jetpack activity and fragment libraries, making it easier to get results from activities by providing type-safe contracts. These contracts define expected input and result types for common actions like taking a picture or requesting a permission, while also providing a way to create your own contracts.

The ActivityResult APIs provide components for registering for an activity result, launching a request, and handling its result once it is returned by the system. You can also receive the activity result in a separate class from where the activity is launched and still rely on the type-safe contracts.

How to use it

To demonstrate how to use the ActivityResult APIs, let’s go over an example where we’re opening a document.

First, you need to add the following dependencies to your gradle file:

repositories {
    google()
    maven()
}

dependencies {
  implementation "androidx.activity:activity:1.2.0-alpha02"
  implementation "androidx.activity:fragment:1.3.0-alpha02"
}

You need to register a callback along with the contract that defines its input and output types.

In this context, GetContent() refers to the ACTION_GET_DOCUMENT intent, and is one of the default contracts already defined in the Activity library. You can find the complete list of contracts here.

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
    // Handle the returned Uri
}

Now we need to launch our activity using the returned launcher. As you can set a mime type filter when listing the selectable files, GetContent.launch() will accept a string as a parameter:

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
    // Handle the returned Uri
}

override fun onCreate(savedInstanceState: Bundle?) {
    // ...

    val selectButton = findViewById<Button>(R.id.select_button)

    selectButton.setOnClickListener {
        // Pass in the mime type you'd like to allow the user to select
        // as the input
        getContent.launch("image/*")
    }
}

Once an image has been selected and you return to your activity, your registered callback will be executed with the expected results. As you saw through the code snippets, ActivityResult brings an easier developer experience when dealing with results from activities.

Start using Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02 for a type-safe way to handle your intent results with the new ActivityResult APIs.

Let us know what you think and how we can make it better by providing feedback on the issue tracker.

Improving inter-activity communication with Jetpack ActivityResult

Posted by Yacine Rezgui, Developer Advocate

Whether you're requesting a permission, selecting a file from the system file manager, or expecting data from a 3rd party app, passing data between activities is a core element in inter-process communication on Android. We’ve recently released the new ActivityResult APIs to help handle these activity results.

Previously, to get results from started activities, apps needed to implement an onActivityResult() method in their activities and fragments, check which requestCode a result is referring to, verify that the requestCode is OK, and finally inspect its result data or extended data.

This leads to complicated code, and it doesn’t provide a type-safe interface for expected arguments when sending or receiving data from an activity.

What are the ActivityResult APIs?

The ActivityResult APIs were added to the Jetpack activity and fragment libraries, making it easier to get results from activities by providing type-safe contracts. These contracts define expected input and result types for common actions like taking a picture or requesting a permission, while also providing a way to create your own contracts.

The ActivityResult APIs provide components for registering for an activity result, launching a request, and handling its result once it is returned by the system. You can also receive the activity result in a separate class from where the activity is launched and still rely on the type-safe contracts.

How to use it

To demonstrate how to use the ActivityResult APIs, let’s go over an example where we’re opening a document.

First, you need to add the following dependencies to your gradle file:

repositories {
    google()
    maven()
}

dependencies {
  implementation "androidx.activity:activity:1.2.0-alpha02"
  implementation "androidx.activity:fragment:1.3.0-alpha02"
}

You need to register a callback along with the contract that defines its input and output types.

In this context, GetContent() refers to the ACTION_GET_DOCUMENT intent, and is one of the default contracts already defined in the Activity library. You can find the complete list of contracts here.

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
    // Handle the returned Uri
}

Now we need to launch our activity using the returned launcher. As you can set a mime type filter when listing the selectable files, GetContent.launch() will accept a string as a parameter:

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
    // Handle the returned Uri
}

override fun onCreate(savedInstanceState: Bundle?) {
    // ...

    val selectButton = findViewById<Button>(R.id.select_button)

    selectButton.setOnClickListener {
        // Pass in the mime type you'd like to allow the user to select
        // as the input
        getContent.launch("image/*")
    }
}

Once an image has been selected and you return to your activity, your registered callback will be executed with the expected results. As you saw through the code snippets, ActivityResult brings an easier developer experience when dealing with results from activities.

Start using Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02 for a type-safe way to handle your intent results with the new ActivityResult APIs.

Let us know what you think and how we can make it better by providing feedback on the issue tracker.

What’s New in Navigation 2020

Posted by Jeremy Woods, Software Engineer, Android UI Toolkit

Navigation image

The latest versions of the Jetpack Navigation library (2.2.0 and 2.3.0) added a lot of requested features and functionality, including dynamic navigation, navigation back stack entries, a library for navigation testing, additional features for deep linking, and more. Let’s go over the most important changes, see what problems they solve, and learn how to use them!

Dynamic Navigation

We’ve updated Navigation to simplify adding dynamic feature modules for your application.

Previously, implementing navigation between destinations defined in dynamic feature modules required a lot of work. Before you could navigate to the first dynamic destination, you needed to add the Play Core library and the Split Install API to your app. You also needed to check for and download the dynamic module. Once downloaded, you could then finally navigate to the destination. On top of this, if you wanted to have an on-screen progress bar for the module being downloaded, you needed to implement a SplitInstallManager listener.

To address this complexity, we created the Dynamic Navigator library. This library extends the functionality of the Jetpack Navigation library to provide seamless installation of on-demand dynamic feature modules when navigating. The library handles all Play Store interaction for you, and it even includes a progress screen that provides the download status of your dynamic module.

The default UI for showing a progress bar when a user navigates to a dynamic feature for the first time.

The default UI for showing a progress bar when a user navigates to a dynamic feature for the first time. The app displays this screen as the corresponding module downloads

To use dynamic navigation, all you need to do is:

  1. Change instances of NavHostFragment to DynamicNavHostFragment
  2. Add an app:moduleName attribute to the destinations associated with a DynamicNavHostFragment

For more information on dynamic navigation, see Navigate with dynamic feature modules and check out the samples.

NavBackStackEntry: Unlocked

When you navigate from one destination to the next, the previous destination and its latest state is placed on the Navigation back stack. If you return to the previous destination by using navController.popBackBack(), the top back stack entry is removed from the back stack with its state still intact and the NavDestination is restored. The Navigation back stack contains all of the previous destinations that were needed to arrive at the current NavDestination.

We manage the destinations on the Navigation back stack by encapsulating them into the NavBackStackEntry class. NavBackStackEntry is now public. This means that users can go a level deeper than just NavDestinations and gain access to navigation-specific ViewModels, Lifecycles, and SavedStateRegistries. You can now properly scope data sharing or ensure it is destroyed at the appropriate time.

See Navigation and the back stack for more information.

NavGraph ViewModels

Since a NavBackStackEntry is a ViewModelProvider, you can create a ViewModel to share data between destinations at the NavGraph level. Each parent navigation graph of all NavDestinations are on the back stack, so your view model can be scoped appropriately:

val viewModel: MyViewModel by navGraphViewModels(R.id.my_graph)

For more information on navGraph scoped view models, see Share UI-related data between destinations with ViewModel

Returning a Result from a destination

By combining ViewModel and Lifecycle, you can share data between two specific destinations. To do this, NavBackStackEntry provides a SavedStateHandle, a key-value map that can be used to store and retrieve data, even across configuration changes. By using the given SavedStateHandle, you can access and pass data between destinations. For example to pass data from destination A to destination B:

In destination A:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    val navController = findNavController();
    // We use a String here, but any type that can be put in a Bundle is supported
    navController.currentBackStackEntry?.savedStateHandle?.getLiveData<String>("key")?.observe(
        viewLifecycleOwner) { result ->
        // Do something with the result.
    }
}

And in destination B:

navController.previousBackStackEntry?.savedStateHandle?.set("key", result)

See Returning a result to the previous Destination for more details.

Testing your Navigation Flow

Previously, the recommended testing solution for Navigation was Mockito. You would create a mock NavController and verify that navigate() was called at the appropriate time with the correct parameters. Unfortunately, this solution was not enough to test certain areas of Navigation flow, such as ViewModel interaction or the Navigation back stack. The Navigation Library now offers a well-integrated solution for these areas with the Navigation Testing library.

The Navigation Testing library adds TestNavHostController, which gives access to the Navigation back stack in a test environment. This means that you can now verify the state of the entire back stack. When using the TestNavHostController, you can set your own LifecycleOwner, ViewModelStoreOwner, and OnBackPressDispatcher by using the APIs given by NavHostController. By setting these components, you can test them in the context of navigation.

For example, here's how to test a destination that uses a nav graph-scoped ViewModel:

val navController = TestNavHostController(ApplicationProvider.getApplicationContext())

// This allows fragments to use by navGraphViewModels()
navController.setViewModelStore(ViewModelStore())
navController.setGraph(R.navigation.main_nav)

The TestNavHostController also lets you set the current destination. You can move the test directly to the use case being tested without the need to set it up using navigate() calls. This is extremely convenient for writing tests for different navigation scenarios.

When setting the current destination, you might do something like the following:

val navController = TestNavHostController(ApplicationProvider.getApplicationContext())

navController.setGraph(R.navigation.main_nav)
navController.setCurrentDestination(R.id.destination_1)

Remember that when setting the current destination, that destination must be part of your nav graph.

For more information about TestNavHostController, see the Test Navigation docs.

Nav Deep Linking

Deep linking allows you to navigate directly to any destination no matter where you currently are in the NavGraph. This can be very useful for launching your app to a specific destination or jumping between destinations that would otherwise be inaccessible to one another.

When navigating using a deep link, you can now provide deep link query parameters in any order and even leave them out altogether if they have been given a default value or have been made nullable. This means that if you have provided default values for all of the query parameters on a deep link, the deep link can match a URL pattern without including any query parameters.

For example, www.example.com?arg1={arg1}&arg2={arg2} will now match with www.example.com as long as arg1 and arg2 have default values and/or are nullable.

Deep links can also be matched using intent actions and MIME types. Instead of requiring destinations to match by URI, you can provide the deep link with an action or MIME type and match with that instead. You can specify multiple match types for a single deep link, but note that URI argument matching is prioritized first, followed by action, and then mimeType.

You create a deep link by adding it to a destination in XML, using the Kotlin DSL, or by using the Navigation Editor in Android Studio.

Here's how to add a deep link to a destination using XML:

<fragment android:id="@+id/a"
          android:name="com.example.myapplication.FragmentA"
          tools:layout="@layout/a">
        <deeplink app:url="www.example.com"
                app:action="android.intent.action.MY_ACTION"
                app:mimeType="type/subtype"/>
    </fragment>

Here's how to add the same deep link using the Kotlin DSL:

val baseUri = "http://www.example.com/"

fragment<MyFragment>(nav_graph.dest.a) {
   deepLink(navDeepLink {
    uriPattern = "${baseUri}"
    action = "android.intent.action.MY_ACTION"
    mimeType = "type/subtype"
   })
}

You can also add the same deep link using the Navigation Editor in Android Studio versions 4.1 and higher. Note that you must also be using the Navigation 2.3.0-alpha06 dependency or later.

An open dialog in the Navigation Editor for adding a deep link to a destination. There are options to add an URI, a MIME type, and an action, along with a checkBox to Auto Verify

Adding a deep link to a destination in the Navigation Editor

To navigate to a destination using a deep link, you must first build a NavDeepLinkRequest and then pass that deep link request into the Navigation controller's call to navigate():

val deepLinkRequest = NavDeepLinkRequest.Builder
        .fromUri(Uri.parse("http://www.example.com"))
        .setAction("android.intent.action.MY_ACTION")
        .setMimeType("type/subtype")
        .build()
navController.navigate(deeplinkRequest)

For more information on deep links, visit Create a deep link for a destination, as well as the deep linking sections in Navigate to a destination and Kotlin DSL.

Navigation Editor

Android Studio 4.0 includes new features for the Navigation Editor. You can now edit your destinations using a split pane view. This means you can edit the XML or design and see the changes in real time.

The Navigation Editor opened in split pane mode with the navigation.xml file on the left and the corresponding nav graph on the right. The nav graph has 6 destination, and a nested graph

Viewing a navigation.xml file in split view mode

In Android Studio 4.1, the Navigation Editor introduced the component tree. This allows you to traverse the entire nav graph, freely going in and out of nested graphs.

An open component tree of a nav graph in the Navigation Editor. It starts viewing the entire graph, then moves to the title screen before going into the nested profiles graph. After cycling through the destinations in the profiles graph, it goes back to fragments in the original graph

Navigating through a graph in the Navigation Editor

Additional Changes

NavigationUI can now use any layout that uses the Openable interface. This means that it is no longer limited to DrawerLayout and allows for customization of the AppBarConfiguration. You can provide your Openable and use it as the layout instead.

Navigation also provides support for Kotlin DSL. Kotlin DSL can be used to create different destinations, actions, or deep links. For more information see the documentation for Kotlin DSL.

Wrap up

Navigation added lots of useful features over the past year. You can simplify your dynamic feature modules by taking advantage of the Dynamic Navigator library, use a NavBackStackEntry to help correctly scope your data, easily test your navigation flow using the TestNavHostController, or even match your deep link using intent actions and/or MIME types.

For more information about the Jetpack Navigation library, check out the documentation at https://developer.android.com/guide/navigation

Please provide feedback (or file bugs) using the Navigation issuetracker component.