Trying to implement an Android share sheet, and following the official docs. The sheet comes up and the sharing works as expected. However, the broadcast receiver never fires. Here is the code:
In the activity class:
// convenience method to create the sheet
var shareSheetIntent = shareSheetIntent(
shareSheetTitleId = R.string.share_sheet_title,
shareSheetImageId = R.drawable.ic_sheet_logo,
messageToShare = messageText
)
val pendingIntent = PendingIntent.getBroadcast(
this,
4321,
Intent(this, MyShareSheetReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
).intentSender
shareSheetIntent = Intent.createChooser(shareSheetIntent, null, pendingIntent)
startActivity(shareSheetIntent)
And then this is my receiver:
class MyShareSheetReceiver : BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
Log.d("hello", "share sheet receiver fired")
}
}
Everything except the receiver works. The messages get sent to the intended recipient, but I don't see onReceive
ever firing. What am I missing?
Edit:
Checking the logcat, I can see this message:
Received BROADCAST intent 0x80a4d6 Key{broadcastIntent pkg=com.example.debug intent=cmp=com.example.debug/com.example.MyShareSheetReceiver flags=0x2000000 u=0} requestCode=4321 sent=0 from uid 1000
I wanted to answer my own question because I believe that the Android docs are missing an incredibly important detail.
I solved this problem by adding the receiver class to the manifest. Nowhere in the documentation of how to send data to other apps (and how to use a broadcast receiver to get a callback) does it mention having to add to the manifest.
Specifically, here is what I did:
In the general documentation on BroadcastReceivers there is discussion of using the context to register the receiver but this seems incompatible for a share sheet receiver due to the use of an IntentFilter, different flags, etc. Nonetheless, the share sheet receiver appears to be a context-registered receiver, which should make registering it in the manifest unnecessary.
So, for anyone else who may have this same issue, give this a try. Hopefully it will solve the problem for you. It did for me.