Step #4: Sharing the Report
To actually share the report, we need to start an ACTION_SEND
activity. ACTION_SEND
is the implicit Intent
action used for most of the “share” options that you see in Android apps. We can provide it with the Uri
to the report, via an EXTRA_STREAM
extra. Usually, a device will have 2+ apps that support ACTION_SEND
for a text/html
MIME type, so frequently the user will get a chooser, asking which of those apps to use. If the user has only one compatible app, or if the user chose a default share target on some past ACTION_SEND
Intent
, then there will be no chooser, and the user will be taken straight to some ACTION_SEND
-supporting activity.
But, there is also the chance that there are zero apps that support ACTION_SEND
for text/html
. You might encounter this on an emulator, for example, which usually has few apps installed. So we need to handle this scenario as well, just as we did in the preceding tutorial, where we needed to handle the case where there was no ACTION_VIEW
Intent
for our content.
In RosterListFragment
, add this shareReport()
function:
private fun shareReport(doc: Uri) {
safeStartActivity(
Intent(Intent.ACTION_SEND)
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.setType("text/html")
.putExtra(Intent.EXTRA_STREAM, doc)
)
}
This is nearly identical to viewReport()
. We create an ACTION_SEND
Intent
, tucking our Uri
into the EXTRA_STREAM
extra. We use setType()
to indicate that this is HTML — this is needed due to the way that ACTION_SEND
needs the Uri
to be in an extra rather than in the main portion of the Intent
the way our ACTION_VIEW
Intent
was set up.
Then, in onOptionsItemSelected()
, add another branch to handle the share
app bar item, routing it to shareReport()
on our RosterMotor
:
R.id.share -> {
motor.shareReport()
return true
}
Finally, in onViewCreated()
of RosterListFragment
, modify the navEvents
collector configuration to look like:
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
motor.navEvents.collect { nav ->
when (nav) {
is Nav.ViewReport -> viewReport(nav.doc)
is Nav.ShareReport -> shareReport(nav.doc)
}
}
}
Now, if you run the app and click the “share” action item, you should get some options for sharing the generated report.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.