Skip to content

Instantly share code, notes, and snippets.

@anayw2001
Created January 10, 2024 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anayw2001/5dfa3a3abfbd071d33851320f39ecc7c to your computer and use it in GitHub Desktop.
Save anayw2001/5dfa3a3abfbd071d33851320f39ecc7c to your computer and use it in GitHub Desktop.
How to use the Nearby Sharing slice
val sliceUri = Uri.parse("content://com.google.android.gms.nearby.sharing/scan")
val sliceManager = SliceViewManager.getInstance(context)
sliceManager.registerSliceCallback(sliceUri, slice -> {
for (targetItem in slice.items.reversed()) {
// Each row containing a target has the hints LIST_ITEM and ACTIVITY.
if (!(targetItem.format == SLICE && targetItem.hints.containsAll(listOf(LIST_ITEM, ACTIVITY)))) {
continue
}
val targetSlice = targetItem.slice
var deviceName: String? = null
var action: PendingIntent? = null
var profileIcon: IconCompat? = null
for (item in targetSlice.items) {
// The slice item of the target's device name contains the TITLE hint.
if (item.format == TEXT && item.hints.contains(TITLE)) {
deviceName = item.text.toString()
}
// The slice item of the target action contains the SHORTCUT and TITLE hints.
if (item.format == ACTION && item.hints.containsAll(listOf(SHORTCUT, TITLE))) {
action = item.action
val iconSlice: Slice? = item.slice
if (iconSlice != null) {
for (iconitem in iconSlice.items) {
// The target's icon is indicated by the IMAGE slice item format and the NO_TINT hint.
if (iconitem.format == IMAGE && iconitem.hints.contains(NO_TINT)) {
profileIcon = iconitem.icon
}
}
}
}
}
// Returns null if the data parsed from the slice is incomplete.
if (deviceName == null || action == null || profileIcon == null) {
continue
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment