Implementing Android Slice
In Android Pie, Google released a new API called Slices. Slices are part of Android Jetpack Support library. Slices are part of smaller UI template to display content of your app in Google Search App. It helps user perform the work at faster rate outside of your app.
In this blog, we will talk about how to implement Slices in your app. Slices supports different LiveData, Deeplink, Scrollable layout etc.
Let's get started
- Before building your own slice you need Android Studio 3.1 and above
- Kotlin version should be above 1.2.30 or above.
Implement your first Slice
Add the dependency in your app's build.gradle
dependencies {
implementation "androidx.slice:slice-builders-ktx:(latest version)"
}
Now, we need to create a file which extends the SliceProvider. It is like to provide slice to app. A slice is a piece of app content and actions that can be displayed outside of the app in Android system surfaces or within another app. Slices are identified by a Uri and a SliceProvider allows your app to provide a slice based on a uri.
To create a new provider, NEW -> OTHERS -> SLICEPROVIDER and as it gets created it will be added in the Manifest.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.app">
...
<application>
...
<provider android:name="MySliceProvider"
android:authorities="com.example.android.app"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.app.slice.category.SLICE" />
</intent-filter>
</provider>
...
</application>
</manifest>
Each Slice has been associated with an URI. So, when app wants to display the slice, it sends the binding request to app with the assocaited URI. Then the app builds the Slice via onBindSlice
OnBindSlice method looks like,
override fun onBindSlice(sliceUri: Uri): Slice? {
val activityAction = createActivityAction()
return if (sliceUri.path == "/hello") {
list(context, sliceUri, ListBuilder.INFINITY) {
row {
primaryAction = activityAction
title = "Hello World."
}
}
} else {
list(context, sliceUri, ListBuilder.INFINITY) {
row {
primaryAction = activityAction
title = "URI not recognized."
}
}
}
}
Now, to see the Slice, we need to setup the SliceViewer.Run the following ,
adb install -r -t slice-viewer.apk
Run the Slice Viewer,
- Click Run -> Edit Configuration
- In this top left corner, click + and select Android App
- Enter Slice in name field and select app in module
- Under launch option, select URL like slice-content://com.app's-package_name/hello
- and click Ok.
Now, run the app from top right side by selecting the slice module and you will see the app's module.
src : Android Developer Website
Slices can also be added, like with interactions likes clicks etc to display toast, log or to navigate to new activity.
Happy Coding :)
Team MindOrks.