2018-11-14 10:31:21
Introduction
With an implicit intent, you active an activity without knowing which app or activity will handle the task.
Conversely, your activity can declare one or more intent filters in the AndroidManifest.xml
file to advertise that the activity can accept implicit intents, and to define the types of intents that the activity will accept.
In this practical we’ll build an app that sends an implicit intent to perform each of the following tasks:
- Open a URL in a web browser.
- Open a location on a map.
- Share text.
- open camera
Open website
fun openWebsite(view: View) {
val url = website_edittext.text.toString()
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
Log.d("ImplicitIntents", "Can't handle this intent!");
}
}
Open location
fun openLocation(view: View) {
val loc = location_edittext.text.toString()
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=$loc"))
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
Log.d("ImplicitIntents", "Can't handle this intent!");
}
}
Share text
fun shareText(view: View) {
val text = share_edittext.text.toString()
val mimeType = "text/plain"
ShareCompat.IntentBuilder
.from(this)
.setType(mimeType)
.setChooserTitle("Share this text with:")
.setText(text)
.startChooser()
}
Take photo
fun openCamera(view: View) {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (intent.resolveActivity(packageManager) != null) {
startActivityForResult(intent, TAKE_PICTURE)
} else {
Log.d("ImplicitIntents", "Can't handle this intent!");
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == TAKE_PICTURE) {
if (resultCode == Activity.RESULT_OK && data != null) {
Log.d(TAG, "onActivityResult: ")
val bitmap = data.extras["data"] as Bitmap
picture.setImageBitmap(bitmap)
}
}
}
Summary
- An implicit
Intent
allows you to activate anActivity
if you know the action, but not the specific app orActivity
that will handle that action. - An
Activity
that can receive an implicitIntent
must defineIntent
filters in theAndroidManifest.xml
file that match one or moreIntent
actions and categories. - The
ShareCompat.IntentBuilder
class makes it easy to build an implicitIntent
for sharing data to social media or email.