Skip to main content

Simplified launching of Android Activities

Extension functions are really great for making life easier, allowing us to add functionality to types that aren't our own. One area we can use an extension is for launching Android Activities more easily.

We can build an extension that allows all Activities to be launched via a generic type argument. An optional request code can be passed to the function, which controls whether startActivity or startActivityForResult is used to launch the Activity. By providing an intent builder function, the Intent that is fired can be customised.

inline fun <reified ActivityT : Activity> Activity.startActivity(
    requestCode: Int? = null,
    intentBuilder: Intent.() -> Unit = {}
) {
    val intent = Intent(this, ActivityT::class.java)
        .apply { intentBuilder() }
    if (requestCode == null) {
        startActivity(intent)
    } else {
        startActivityForResult(intent, requestCode)
    }
}

fun startContactCreation(fromActivity: Activity, requestCode: Int) {
    fromActivity.startActivity<ConnectionCreationActivity>(requestCode) {
        putExtra("source", ConnectionCreationSource.CONNECTIONS)
    }
}

I hope the article was useful. If you have any feedback or questions please feel free to reach out.

Thanks for reading!

Like what you read? Please share the article.

Avatar of Andrew Lord

WRITTEN BY

Andrew Lord

A software developer and tech leader from the UK. Writing articles that focus on all aspects of Android and iOS development using Kotlin and Swift.

Want to read more?

Here are some other articles you may enjoy.