Android Slices: Getting Started

In this tutorial, you’ll learn how to use Slices, which allow you to embed parts of your app into viewers like the Google Search app and Google Assistant. By Ahmed Tarek.

Leave a rating/review
Download materials
Save for later
Share

At Google I/O 2018, Google announced a new way to present UI templates that can display rich, dynamic and interactive content from your app within the Google Search app and, later, in other places such as the Google Assistant.

Those UI templates are called Slices. The templates are great for many reasons:

  • Slices can help users to get information or take instant action outside of an app screen.
  • Slices make your users re-engage with your app in a relevant context.
  • Slices are built into Android Jetpack and can extend all the way back to Android Kitkat API 19.

Slices are in beta release at the time of writing this tutorial, but you can get started developing with them today!

Getting Started

In this tutorial you are going to build a Slice template for a raywenderlich.com Bookstore app. The Slice will display some book covers with titles and prices, as well as a notification icon to enable or disable the app notification. Here’s what the end product will look like:

Finished Slice

If you’re completely new to Android, you might want to first check out Beginning Android Development Part One. If you need to catch up on Kotlin, you can check out Kotlin for Android: An Introduction.

Prerequisites: For this tutorial, you need basic knowledge of Android programming and familiarity with Kotlin and Android Studio. Knowledge of content providers and URIs is helpful but not required.

If you’re completely new to Android, you might want to first check out Beginning Android Development Part One. If you need to catch up on Kotlin, you can check out Kotlin for Android: An Introduction.

To follow along with this tutorial, you’ll need to use Android Studio 3.1.3 or later and Kotlin 1.2.30 or later.

Start by downloading the materials for this tutorial using the Download Materials button at the top or bottom of this page. Fire up Android Studio and import the starter project. For the most part, you will create your own classes. You will need to find AndroidManifest.xml to add code, so make sure you can locate that.

If you have not downloaded the SDK for Android API Level 28 previously, you’ll have to do that to run the app. If you already have Android API 28 set up, you can skip the following four steps and go right to building and running the app.

In the SDK Platforms tab, select Android SDK Platform 28.

In the SDK Tools tab, select Android SDK Build-Tools 28-rc2

  1. Select Tools ▸ SDK Manager, or click the SDK Manager icon in toolbar.
  2. In the SDK Platforms tab, select Android API 28. You may need to select “Show Package Details” to see it.
    In the SDK Platforms tab, select Android 28.

    In the SDK Platforms tab, select Android SDK Platform 28.

  3. In the SDK Tools tab, select Android SDK Build-Tools 28-rc2 or higher. Again, you may need to select “Show Package Details.”
    In the SDK Tools tab, select Android SDK Build-Tools 28-rc2

    In the SDK Tools tab, select Android SDK Build-Tools 28-rc2

  4. Click OK to begin install.
In the SDK Platforms tab, select Android 28.

In the SDK Platforms tab, select Android SDK Platform 28.

In the SDK Tools tab, select Android SDK Build-Tools 28-rc2

In the SDK Tools tab, select Android SDK Build-Tools 28-rc2

Once the SDK is installed, build and run the app. It is a bookstore app, and it shows the available books on https://store.raywenderlich.com/.

Bookstore app

Slice Viewer

Android Teacher
Slices need a viewer or presenter to display their content.

The Google Search app is one of the suitable presenters to show your Slice template. When the user types a word in the search bar, the Slice you’ve created might present related information to the user’s search keyword.

For example, if the user types words such as “ride” or “ride car,” Slices from installed apps like Careem or Uber could show to let the user request a car even without opening the corresponding app; that full experience can be achieved by App Actions and Slices.

Displaying Your Slice With Slice Viewers

Bear in mind that presenters may make a light customization to your Slices to match their design requirements, e.g., font style, font size and/or colors. Icons in your Slice, for example, will be tinted with the accent color of the presenter app.

You will use a Slice Viewer app to display the Slice from your Bookstore app. The Slice Viewer app uses your slice Uri to view it on what’s called its surface, and on a first time request of your Slice, the user will be asked to grant a permission to the viewer.

Installing the Slice Viewer App

Install the SliceViewer.apk, which can be found in the downloaded materials for this tutorial, on a real device or emulator, then open the app. You can install the APK file by dragging and dropping the file onto the emulator if you’re using one or running adb install -r -t SliceViewer.apk from the terminal while in that directory. The Slice Viewer app looks like this:

Slice Viewer app

Creating the BookstoreSliceProvider Class

The starter project already includes the Slices core and builders libraries as dependencies in the app’s build.gradle file, so you can get started right away building your Slice:

implementation "androidx.slice:slice-core:1.0.0-beta01"
implementation "androidx.slice:slice-builders:1.0.0-beta01"

Create a new Kotlin class named BookstoreSliceProvider and make it inherit from the androidx.slice.SliceProvider class. Use the androidx option if available for any imports that you need to add for the rest of the tutorial.

import androidx.slice.SliceProvider

class BookstoreSliceProvider: SliceProvider() {

}

Implementing the SliceProvider Class

The SliceProvider class is your only way to expose your Slice to other apps, and it decides which Slice will be exposed to the viewer.

The SliceProvider class is a subclass of the ContentProvider class. Content providers are one of the primary building blocks of Android applications. They encapsulate data and provide it to applications through the single ContentResolver interface. You can use content providers if you need to share data between multiple apps. For example, Contacts data is used by multiple apps and is stored in a content provider. Learn more about content providers from here.

Add two methods to your BookstoreSliceProvider, along with a companion object. You’ll add the createBookstoreSlice() function shortly:

// 1
override fun onCreateSliceProvider(): Boolean {
 // 2
 return true
}

// 3
override fun onBindSlice(sliceUri: Uri): Slice? {
 //4
 val path = sliceUri.path
 when (path) {
 // 5
   "/$BOOKSTORE_PATH" -> return createBookstoreSlice(sliceUri)
 }
 // 6
 return null
}

companion object {
   // 7
  const val BOOKSTORE_PATH = "book_store"
}

Here, you:

  1. Implement onCreateSliceProvider() to initialize your Slice provider on startup. Do not put long running operations here or your app launch will be delayed, and the first Slice that binds with the viewer will be delayed, too.
  2. Return true if the provider was successfully loaded, false otherwise.
  3. Create your Slice inside the body of onBindSlice(). You should create and return your Slice as quickly as possible. If you want to make network requests or I/O operations, do so in the background to keep your Slice UI responsive. If your background operation is done and you want to update your Slice with the new data, call contentResolver.notifyChange(uri) with the Slice URI, and Android will invoke onBindSlice() for you.
  4. Get the path from the URI.
  5. Check if that path is the path of your Slice and return the bookstore Slice if true.
  6. Return null in case you have no Slice for this path.
  7. Create a String constant as a bookstore path.

Slice providers must be registered in the app Android manifest, so declare BookstoreSliceProvider in the AndroidManifest.xml file as a child of the application element.

<provider
  android:name=".BookstoreSliceProvider"
  android:authorities="com.raywenderlich.android.bookstore"
  android:exported="true"
  android:grantUriPermissions="true"/>

You’ve marked the Slice provider as exported so that it is made available to Slice viewers.