Implicit Intents — Asking Other Apps
Sprout should let users share watering tips with a friend. You could build a messaging feature... or ask the phone's existing apps to do it. Android was designed for the second option.
The rule
Say what to do, not who does it; the system finds the app.
An implicit intent names no class. It describes the job with an action and, usually, some data or a type. The system searches installed apps for one that has declared it can do that job.
val send = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, "Water the Monstera every 7 days")
}
startActivity(Intent.createChooser(send, "Share tips"))Common actions:
ACTION_VIEWwith a URI — show something:https://opens a browser,geo:a map.ACTION_SENDwith a MIME type — share content.ACTION_DIALwithtel:— open the dialer with a number filled in.
If several apps match, the user picks one. createChooser always shows the picker, which is friendlier for sharing. If no app matches, startActivity throws ActivityNotFoundException, so guard it:
try { startActivity(view) }
catch (e: ActivityNotFoundException) { showMessage("No app can open this") }