Streamlining intents with Kotlin coroutines

companion object {
const val RC_GET_IMAGE = 0
}
fun getImage() {
val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
type = "image/*"
}

if (intent.resolveActivity(packageManager) == null) {
return
}
startActivityForResult(intent, RC_GET_IMAGE)
}
override fun onActivityResult(requestCode: Int,
resultCode: Int, data: Intent?) {
if (requestCode == RC_GET_IMAGE
&& resultCode == Activity.RESULT_OK) {
data?.let {
val bitmap = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), it.data);
myImageView.setImageBitmap(bitmap)
}
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
  1. First of all, we need to define a special constant RC_GET_IMAGE, only for the purpose of determining, in onActivityResult, what request was originally launched.
  2. Second, when launching the ACTION_GET_CONTENT activity in getImage(), we need to check if the activity is actually available using resolveActivity()
  3. Finally, we need to override a separate method, onActivityResult(), check if the requestCode matches our special RC_GET_IMAGE constant and only the process the result available in data.

Introducing AsyncActivity

The following class takes care of the mechanics of launching activities, tracking requestCodes and firing deferred completions:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0'

Launching activity with coroutines

Now that your code is using AsyncActivity, launching an activity becomes much simpler:

val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
type = "image/*"
}

GlobalScope.launch(Dispatchers.Main) {
val
result = launchIntent(intent).await()
result?.data?.let {
val
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), it.data);
myImageView.setImageBitmap(bitmap)
}
}

--

--

Write code for fun and living

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store