Handling Back Presses in Jetpack Compose and OnBackInvokedCallback

Photo by Firmbee.com on Unsplash
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.d("TAG", "OnBackPressed")
}
}
BackHandler(true) {
Log.d("TAG", "OnBackPressed")
}
android:enableOnBackInvokedCallback="true"
@Composable
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
fun BackInvokeHandler(
handleBackHandler: Boolean,
priority : Int = OnBackInvokedDispatcher.PRIORITY_DEFAULT,
callback : () -> Unit = {}
) {
val backInvokedCallback = remember {
OnBackInvokedCallback {
callback()
}
}

val activity = when(LocalLifecycleOwner.current) {
is MainActivity -> LocalLifecycleOwner.current as MainActivity
is Fragment -> (LocalLifecycleOwner.current as Fragment).requireActivity() as MainActivity
else -> {
val context = LocalContext.current
if (context is MainActivity) {
context
} else {
throw IllegalStateException("LocalLifecycleOwner is not MainActivity or Fragment")
}
}
}

if (handleBackHandler) {
activity.onBackInvokedDispatcher.registerOnBackInvokedCallback(priority, backInvokedCallback)
}

LaunchedEffect(handleBackHandler) {
if (!handleBackHandler) {
activity.onBackInvokedDispatcher.unregisterOnBackInvokedCallback(backInvokedCallback)
}
}

DisposableEffect(activity.lifecycle, activity.onBackInvokedDispatcher) {
onDispose {
activity.onBackInvokedDispatcher.unregisterOnBackInvokedCallback(backInvokedCallback)
}
}
}

--

--

Software Engineer, Mobile Developer. @Univerlist/@Univenn

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