Skip to content

Instantly share code, notes, and snippets.

@passsy
Last active Oct 17, 2021
Embed
What would you like to do?
Kotlin extension functions to start a generic Activity
package com.pascalwelsch.extensions
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
/**
* Extensions for simpler launching of Activities
*/
inline fun <reified T : Any> Activity.launchActivity(
requestCode: Int = -1,
options: Bundle? = null,
noinline init: Intent.() -> Unit = {}) {
val intent = newIntent<T>(this)
intent.init()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startActivityForResult(intent, requestCode, options)
} else {
startActivityForResult(intent, requestCode)
}
}
inline fun <reified T : Any> Context.launchActivity(
options: Bundle? = null,
noinline init: Intent.() -> Unit = {}) {
val intent = newIntent<T>(this)
intent.init()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startActivity(intent, options)
} else {
startActivity(intent)
}
}
inline fun <reified T : Any> newIntent(context: Context): Intent =
Intent(context, T::class.java)
@passsy
Copy link
Author

passsy commented Jul 20, 2020

I use both. If you provide a requestCode it calls startActivityForResult otherwise startActivity

@denebchorny
Copy link

Yep, I did research, and it's funny what I found. StartActivity calls startActivityForResult internally; then, it means that we would say its the same.

public void startActivity(Intent intent, @nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}

@passsy
Copy link
Author

passsy commented Jul 20, 2020

It's important to call the correct method though. startActivity might be overridden or - unlikely - the internal implementation might change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment