Skip to content

Instantly share code, notes, and snippets.

@raxityo
Created April 30, 2020 23:51
Show Gist options
  • Save raxityo/cb967cb9cb0d035c7bca1c5046f702ea to your computer and use it in GitHub Desktop.
Save raxityo/cb967cb9cb0d035c7bca1c5046f702ea to your computer and use it in GitHub Desktop.
Navigate up to the parent activity if it's declared in the manifest and start the new task if needed.
import android.app.Activity
import androidx.core.app.NavUtils
import androidx.core.app.TaskStackBuilder
/**
* Navigate up to the parent activity if it's declared in the manifest and start the new task if
* needed.
*
* @see [NavUtils.shouldUpRecreateTask]
* @receiver Activity
*/
fun Activity.navigateUpToParent() {
// Obtain parent activity's intent
NavUtils.getParentActivityIntent(this)
?.let {
// Only attempt to go ahead if `NavUtils` tells us or this is the root of task
if (NavUtils.shouldUpRecreateTask(this, it) || isTaskRoot)
// Build stack that launches parent activity.
TaskStackBuilder
.create(this)
.addNextIntentWithParentStack(it)
.startActivities()
else // No need to recreate the task.
NavUtils.navigateUpTo(this, it)
}
?: finish() // Fallback: Parent activity not defined.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment