Detecting which app was used to share your apps content

Kumar Bibek
2 min readMay 7, 2021

Almost all mobile apps do some sort of sharing data with other apps. For example, your app might want to share URLs, images, videos or text content to other apps like Facebook, Twitter, Gmail and so on.

To implement this, it’s quite straight-forward. You create an Intent with the action as ACTION_SEND, provide it with the data you want to share. You then create a chooser intent, and then pass this intent to the startActivity() method.

Something like this, which is the recommended way:

val intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, "This is my text to send.")
type = "text/plain"
}
val share = Intent.createChooser(intent, null)
startActivity(share)

This will bring up the “Android Sharesheet” which will show a list of applications that can handle the type of data that you provide.

But, what if you want to know which application the user chose to share your content? This could be a piece of analytics data that you might want to track so that you can may be create your marketing campaigns.

The Android Sharesheet enables this by providing the ComponentName of targets your users click via an IntentSender.

You can create a PendingIntent to a BroadcastReceiver that will be triggered when a user makes a choice in the Sharesheet.

So, your code will look like this:

val intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, "This is my text to send.")
type = "text/plain"
}

val
pi = PendingIntent.getBroadcast(
activity, 100,
Intent(activity, ShareIntentReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT
)

val share = Intent.createChooser(intent, null, pi.intentSender)
startActivity(share)

The code for ShareIntentReceiver:

class ShareIntentReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val clickedComponent: ComponentName? = intent?.getParcelableExtra(EXTRA_CHOSEN_COMPONENT);
Log.i("ShareIntentReceiver", "Component name: $clickedComponent")
}
}

And of course, you will need to register this broadcast receiver in your manifest file.

When the user makes a choice, the name of the component will be sent in the onReceive method of your broadcast receiver. You can now record this in your analytics service or send it to your backend for further analysis/processing.

--

--

Kumar Bibek

While my phone and the laptop is being charged, I love to write, cook and ride away from the city on my bicycle.