Sharing in Android 10: Getting Started

In this Sharing in Android 10 tutorial, you’ll learn how to use the Sharing Shortcuts API to receive and share images in an app. By Gordan Glavaš.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 2 of 2 of this article. Click here to view the first page.

Publishing Your Shortcuts

Before you can see your shortcuts while using other apps, you need to publish them. To do this, add this method to ShareUtil.kt:

fun publishMemeShareShortcuts(context: Context) {
  ShortcutManagerCompat.addDynamicShortcuts(context, Category.values()
      .take(ShortcutManagerCompat.getMaxShortcutCountPerActivity(context))
      .map { it.toShortcut(context) }
  )
}

Then, invoke it at the end of MainActivity.kt onCreate:

ShareUtil.publishMemeShareShortcuts(this)

Effectively, the above two snippets of code publish the list of shortcuts to the Android sharing system. If there are already dynamic or pinned shortcuts with the same IDs, each mutable shortcut is updated.

Build and run, then try to share the image again. This time, you’ll see the sharing shortcuts for your meme categories.

Sharing shortcuts with meme categories

The shortcuts work, but not quite like you intended. The category still defaults to Classic. You’ll fix that next.

Finishing Your Shortcuts

To make everything come together, open MemeActivity.kt and replace the TODO in onCreate with this code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
  val id = intent.getStringExtra(Intent.EXTRA_SHORTCUT_ID) 
  if (id?.isNotEmpty() == true) { 
    category.setSelection(Category.positionFor(id))
  }
}

This code checks if the share intent contains a shortcut ID, which you set by navigating to MemeActivity via a sharing shortcut, and then selects the category.

Build and run. Now, sharing an image to your app via a sharing shortcut will properly share both the image URL and the selected category:

Shared image with URL and category

Sharing shortcuts also give you an extra advantage: Long-press the app icon and you’ll see that you sharing shortcuts appear there as well:

Sharing shortcuts in the long-press menu

Pull or Push?

If you’re an Android user, you might have noticed that after you try to share something, the share sheet takes a while to appear.

This happens because, prior to Android 10, all the sharing shortcuts were on-demand. You’d decide to share something and then the OS would prompt the apps to provide their list of shortcuts for the specific sharing target. Call this the pull model.

Android 10 Sharing Shortcuts API solves this issue by opting for a push model. Apps dynamically publish shortcuts at runtime, which means that the entire share sheet is ready as soon as you decide to share something. This eliminates any lag.

So how do these two conflicting models work together if you deploy your Android 10 app on a device running an older Android version? Well, AndroidX has your back: Using ShortcutInfoCompat and ShortcutManagerCompat assures that your sharing shortcuts code will work properly on all devices and OS versions.

Making Your App Stable

Creating the shortcuts dynamically means that you have to be more careful about some details. For example, you probably noticed this line in publishMemeShareShortcuts:

.take(ShortcutManagerCompat.getMaxShortcutCountPerActivity(context))

There’s a hard limit of four sharing shortcuts per Activity. The exact behavior varies between devices, but on some, publishing more than four sharing shortcuts will result in a crash.

To make sure you’re safe, add this method to ShareUtil:

fun unPublishMemeShareShortcuts(context: Context) {
  ShortcutManagerCompat.removeAllDynamicShortcuts(context)
}

Then, invoke it on onDestroy() in MainActivity:

override fun onDestroy() {
  super.onDestroy()
  ShareUtil.unPublishMemeShareShortcuts(this)
}

This prevents any duplicated sharing categories, and prevents too many sharing shortcuts from being displayed to the user.

Build and run, even though there’s nothing new to see, you can sleep peacefully at night knowing that your app won’t crash, even on older devices. :]

Sleeping peacefully now that your app is stable

With the ability to share to your app, in the next section, you’ll focus on sharing from your app to other apps.

Sharing a Meme From Your App

A meme collection is pointless if you can’t share it with your friends, right? Your next step will be to implement the capability to share memes directly from your app.

Start by updating ShareUtil.kt with this code:

//1
private const val FILE_PROVIDER= "com.raywenderlich.android.memerepo.FileProvider" 

fun shareMeme(context: Context, meme: Meme) {
  //2
  val intent = Intent(Intent.ACTION_SEND).apply { 
    //3
    type = "image/jpeg"
    //4
    putExtra(Intent.EXTRA_TITLE, meme.title)
    //5
    val uri = Uri.parse(meme.url) 
    putExtra(Intent.EXTRA_STREAM, uri)
    //6
    clipData = ClipData.newUri(context.contentResolver, context.getString(R.string.app_name),FileProvider.getUriForFile(context, FILE_PROVIDER, File(meme.url)))
    //7
    flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
  }
  //8
  context.startActivity(Intent.createChooser(intent, null)) 
}

Here’s a step-by-step walk-through of this code:

  1. The app’s file provider name, which is the same as the one you used in AndroidManifest.xml.
  2. Sharing requires a custom intent whose action must be Intent.ACTION_SEND.
  3. MIME type is always image/jpeg because the repo saves all the memes locally as JPEGs.
  4. Sets the share sheet title.
  5. Resolves the meme’s local URL and adds it to the intent as Intent.EXTRA_STREAM.
  6. ClipData allows the share sheet to show a snippet of the shared content.
  7. You need this flag to let the intent read local data and stream the image content to another app.
  8. Starts the share sheet.

Now, you’ve set up the ability to share your memes, but tapping on an image still does nothing. You still need to wire everything up.

Sharing When You Tap Images

The final step is to invoke sharing when you tap a meme. Open MemesAdapter.kt and update the class ViewHolder on the bind with the following:

view.setOnClickListener {
  ShareUtil.shareMeme(view.context, meme)
}

Build and run one final time. Tap on any meme in your collection and the share sheet appears.

Sharing images with Meme Repo

Wasn’t that easy? Sharing really is caring!

Where to Go From Here?

Congratulations! On top of learning how to share and receive data between apps, you created a nice Meme Repo app that you can use every day!

You can download the final version of this project using the Download Materials button at the top or bottom of this tutorial.

Learn more details about Android 10 sharing from the official Android guides.

The Meme Repo app relies on GridView to render the meme collection. Learn more about using this component in our Android GridView Tutorial.

You can also learn more about intents in general from our Android Intents Tutorial with Kotlin.

We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!