Skip to content
Muhammed Ali
Kocabey

From onBackPressed to OnBackPressedDispatcher: A New Era in Android Back Handling

Hello, Android developers!

There is always something new to learn in the Android ecosystem. In this post I want to go over a change in how we handle the back button: the move from the onBackPressed function to onBackPressedDispatcher, and how it makes back handling more flexible and easier to maintain.

I tried to keep it useful both for experienced developers and for people who are new to the topic, so the technical details come with concrete examples.

Table of Contents

  • Introduction
  • The History and Limitations of onBackPressed
  • OnBackPressedDispatcher: The New Approach
  • Advantages of Using OnBackPressedDispatcher
  • Back Handling with OnBackPressedDispatcher
    • Implementation in an Activity
    • Implementation in a Fragment
  • Getting Rid of Code Duplication: Extension Functions
    • Extension Function for Activity
    • Extension Function for Fragment
  • Lifecycle Management and Memory Leaks
  • Conclusion and Best Practices
  • 2026 Note: Predictive Back and OnBackInvokedCallback
  • Resources

Introduction

How users interact with the back button has a direct effect on the overall experience of your app. In the past, we overrode the onBackPressed function to decide what happens when the back button is pressed. That approach had its limits, especially in more complex screens: code duplication, awkward lifecycle handling and memory leaks were some of the problems.

To address these, the Android team introduced OnBackPressedDispatcher, which makes back handling more flexible and easier to maintain. In this post we'll look at why onBackPressed was deprecated, how to use OnBackPressedDispatcher in its place, and how Kotlin extension functions make the new approach even simpler to use.

The History and Limitations of onBackPressed

What Is onBackPressed?

onBackPressed is a callback that Android calls when the user presses the back button. By overriding it, you define what should happen at that moment.

override fun onBackPressed() {
    // What to do when the back button is pressed
    finish()
}

Limitations

Using onBackPressed came with a few limitations:

  1. Code duplication: Overriding onBackPressed in every Activity and forwarding the event to Fragments by hand (Fragments don't have their own onBackPressed method) leads to duplicated code and makes maintenance harder.
  2. Lifecycle management: Handling back events in line with the lifecycle can be tricky, which leads to bugs and unexpected behavior.
  3. Lack of modularity: When several components need to handle back events, the code gets complicated and hard to manage.
  4. Memory leaks: Poor lifecycle handling can leave callbacks registered when they should have been removed, which can cause memory leaks.

To solve these problems, the Android team offered a different way: OnBackPressedDispatcher.

OnBackPressedDispatcher: The New Approach

OnBackPressedDispatcher is part of Android Jetpack and was built to make back handling more flexible and modular. It lets us handle back events by registering lifecycle-aware callbacks, so back handling follows the lifecycle of the Activity or Fragment.

Why OnBackPressedDispatcher?

  • Lifecycle integration: Callbacks are managed automatically according to the lifecycle of the Activity or Fragment.
  • Flexibility: You can register more than one back handler.
  • Modularity: Different components can handle back events independently.
  • Less duplication: Common setup code can be moved into extension functions.

As a result, back handling is easier to maintain and the code stays cleaner and easier to follow.

Advantages of Using OnBackPressedDispatcher

  1. Lifecycle awareness: OnBackPressedDispatcher manages callbacks based on the lifecycle, so when the Activity or Fragment is destroyed the callbacks are removed automatically.
  2. Modularity: Different components can add and manage their own back handling, which keeps the code modular.
  3. Less duplication: With extension functions, we can cut down the repeated code around back handling.
  4. Cleaner, more readable code: Back handling gets a more organized structure that is easier to read.

Back Handling with OnBackPressedDispatcher

Implementation in an Activity

Using OnBackPressedDispatcher in an Activity is straightforward. Here are the steps:

1. Define an OnBackPressedCallback:

First, create an OnBackPressedCallback that describes what should happen when the back button is pressed.

val callback = object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // What to do when the back button is pressed
        finish()
    }
}

2. Add the callback to the dispatcher:

Then register the callback with the OnBackPressedDispatcher.

onBackPressedDispatcher.addCallback(this, callback)

3. Putting it together:

Here is an example Activity with all the steps combined:

class ExampleActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_example)

        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // What to do when the back button is pressed
                finish()
            }
        }

        onBackPressedDispatcher.addCallback(this, callback)
    }
}

Implementation in a Fragment

Using OnBackPressedDispatcher in a Fragment is a bit different, because Fragments have their own lifecycle and the callback has to be added at the right time.

1. Define an OnBackPressedCallback:

First, create an OnBackPressedCallback that describes what should happen when the back button is pressed.

val callback = object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // What to do when the back button is pressed
        findNavController().popBackStack()
    }
}

2. Add the callback to the dispatcher:

Then register the callback with the OnBackPressedDispatcher. In a Fragment, this should be tied to the view lifecycle.

requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, callback)

3. Putting it together:

Here is an example Fragment with all the steps combined:

class ExampleFragment : Fragment(R.layout.fragment_example) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // What to do when the back button is pressed
                findNavController().popBackStack()
            }
        }

        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, callback)
    }
}

This way the callback follows the Fragment's view lifecycle and is removed automatically when the Fragment's view is destroyed.

Getting Rid of Code Duplication: Extension Functions

Avoiding duplicated code matters, especially for something as common as back handling: the less you repeat it, the easier the code is to read and maintain. Kotlin extension functions help here by putting the shared setup in one place.

Back Handling with Extension Functions

Extension functions let us add new functions to existing classes. We can use them to build a shared helper for back handling and stop repeating the same code.

Extension Function for Activity

The following extension function makes it easy to attach back-press behavior to an Activity.

/**
 * Adds an action to run when the back button is pressed in an Activity.
 *
 * @param enabled Whether the callback is enabled initially. Defaults to `true`.
 * @param handleOnBackPressed Lambda (a function type with receiver) called when the back button is pressed.
 * Inside it you can access the Activity's members directly.
 */
fun ComponentActivity.addOnBackPressedCallback(
    enabled: Boolean = true,
    handleOnBackPressed: ComponentActivity.() -> Unit
) {
    onBackPressedDispatcher.addCallback(
        this,
        object : OnBackPressedCallback(enabled) {
            override fun handleOnBackPressed() {
                this@addOnBackPressedCallback.handleOnBackPressed()
            }
        }
    )
}

Extension Function for Fragment

The following extension function does the same for a Fragment.

/**
 * Adds an action to run when the back button is pressed in a Fragment.
 *
 * @param enabled Whether the callback is enabled initially. Defaults to `true`.
 * @param handleOnBackPressed Lambda (a function type with receiver) called when the back button is pressed.
 * Inside it you can access the Fragment's members directly.
 */
fun Fragment.addOnBackPressedCallback(
    enabled: Boolean = true,
    handleOnBackPressed: Fragment.() -> Unit
) {
    requireActivity().onBackPressedDispatcher.addCallback(
        viewLifecycleOwner,
        object : OnBackPressedCallback(enabled) {
            override fun handleOnBackPressed() {
                this@addOnBackPressedCallback.handleOnBackPressed()
            }
        }
    )
}

With these extension functions, back handling in Activities and Fragments becomes cleaner and easier to read. For example, to show a confirmation dialog when the back button is pressed in an Activity:

class ExampleActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_example)

        addOnBackPressedCallback {
            showExitConfirmationDialog()
        }
    }

    private fun showExitConfirmationDialog() {
        AlertDialog.Builder(this)
            .setTitle("Are you sure you want to exit?")
            .setMessage("You may have unsaved changes.")
            .setPositiveButton("Yes") { _, _ ->
                finish()
            }
            .setNegativeButton("No", null)
            .show()
    }
}

That keeps back handling simple and removes the duplicated setup code.

Lifecycle Management and Memory Leaks

When you use OnBackPressedDispatcher and OnBackPressedCallback, handling the lifecycle correctly is what keeps you away from memory leaks. In our extension functions, we pass viewLifecycleOwner or a LifecycleOwner so the callbacks stay tied to the lifecycle. When the Activity or Fragment is destroyed, the callbacks are removed automatically.

Usage Example

fun Fragment.addOnBackPressedCallback(
    enabled: Boolean = true,
    handleOnBackPressed: Fragment.() -> Unit
) {
    requireActivity().onBackPressedDispatcher.addCallback(
        viewLifecycleOwner,
        object : OnBackPressedCallback(enabled) {
            override fun handleOnBackPressed() {
                this@addOnBackPressedCallback.handleOnBackPressed()
            }
        }
    )
}

With this setup, the callback is only active during the Fragment's view lifecycle. When the Fragment's view is destroyed, the callback is removed automatically, so no stale callback stays in memory and causes a leak.

Conclusion and Best Practices

Using onBackPressedDispatcher instead of the onBackPressed method makes back handling more flexible and easier to maintain. To get the most out of it, avoid duplicated code and manage the lifecycle correctly. Kotlin extension functions help with both and keep your code clean and readable.

Best Practices

  1. Use extension functions:
    • Move the shared back-handling code into extension functions instead of repeating it.
    • This keeps back handling in Activities and Fragments clean and easy to follow.
  2. Be lifecycle-aware:
    • Use LifecycleOwner and viewLifecycleOwner so callbacks follow the lifecycle.
    • That way, callbacks are removed automatically when the Activity or Fragment is destroyed, and you avoid memory leaks.
  3. Avoid duplication:
    • Abstract your shared code with extension functions to keep it modular and easy to maintain.
  4. Watch out for memory leaks:
    • Keep callbacks tied to the lifecycle.
    • Poor lifecycle handling can leave unnecessary callbacks in memory and lead to performance problems.
  5. Readability and maintainability:
    • Organize your code into small, understandable pieces so it is easier to maintain.
    • Use extension functions to make back handling more readable.

In Short

  • onBackPressed was deprecated in Android 13 (API 33), and OnBackPressedDispatcher took its place.
  • OnBackPressedDispatcher lets you work with lifecycle-aware callbacks.
  • Kotlin extension functions remove duplicated back-handling code and give you a cleaner structure.
  • Pay attention to lifecycle management to avoid memory leaks.

2026 Note: Predictive Back and OnBackInvokedCallback

This section was added after the post was first published. The code above still works; what changed is how the platform handles the back gesture.

  • Activity.onBackPressed() was deprecated in Android 13 (API 33). Its platform counterpart is OnBackInvokedDispatcher with OnBackInvokedCallback. AndroidX's OnBackPressedDispatcher hooks into that platform API by itself on Android 13 and higher, so if you use AndroidX you don't need to write an OnBackInvokedCallback separately.
  • Predictive back is enabled by adding android:enableOnBackInvokedCallback="true" to the <application> tag in the manifest (from Android 14 you can also set it on individual <activity> tags). When it is on, the system no longer calls onBackPressed() and doesn't dispatch KEYCODE_BACK, so code that relies on overriding onBackPressed() quietly stops working. For apps targeting Android 16 (API 36), this behavior is on by default.
  • An always-enabled callback (OnBackPressedCallback(true)) blocks the system's back animations, such as the back-to-home preview. Enable the callback only when you actually need to intercept back, and toggle it with isEnabled. For the exit confirmation dialog above, for example, it's better to keep the callback enabled only while there are unsaved changes. A callback that only calls finish() is usually unnecessary too, because the default back behavior already covers it.
  • OnBackPressedCallback now also offers handleOnBackStarted, handleOnBackProgressed and handleOnBackCancelled. You can use them if you want to build your own in-app back animation.
  • Because the Fragment extension uses viewLifecycleOwner, call it in onViewCreated (or later). If you call it before the view exists, for example in onCreate, you'll get an IllegalStateException.

Resources

Frequently asked questions

Why was onBackPressed deprecated, and what replaced it?
Activity.onBackPressed() was deprecated in Android 13 (API 33). Overriding it in every Activity and forwarding the event to Fragments by hand led to code duplication, lifecycle problems and poor modularity. On the AndroidX side it was replaced by OnBackPressedDispatcher, which works with lifecycle-aware callbacks; the platform-level counterpart is OnBackInvokedCallback.
How do you handle the back button in a Fragment with OnBackPressedDispatcher?
In onViewCreated you create an OnBackPressedCallback and register it with requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, callback). Because the callback is tied to viewLifecycleOwner, it is removed automatically when the Fragment's view is destroyed.
How does OnBackPressedDispatcher help prevent memory leaks?
Callbacks are bound to a LifecycleOwner or viewLifecycleOwner and are managed together with that lifecycle. When the Activity or the Fragment's view is destroyed, the callback is removed automatically, so stale callbacks don't stay in memory.
How can you avoid code duplication when adding back handling?
The post defines Kotlin extension functions named addOnBackPressedCallback for ComponentActivity and Fragment. Instead of repeating the same callback boilerplate on every screen, you add back behavior with a single, readable call.

WORK TOGETHER

Let’s start with a good problem.

Looking for an Android engineer for your team, or someone to think through a technical problem with? Let’s talk.

Book a 30-minute conversation[email protected]All contact and podcast links