Home > Software engineering >  onBackPressed() deprecated, What is the alternative?
onBackPressed() deprecated, What is the alternative?

Time:06-16

I have upgraded targetSdkVersion and compileSdkVersion to 33.

Now getting warning onBackPressedDeprecated

CodePudding user response:

You can use the OnBackInvokedCallback

OnBackInvokedCallback as described in the documentation and follow this guide here to update your code

CodePudding user response:

According your API level register:

This requires to at least use appcompat:1.6.0-alpha03; the current is 1.6.0-alpha04:

 implementation 'androidx.appcompat:appcompat:1.6.0-alpha04'
if (BuildCompat.isAtLeastT()) {
    onBackInvokedDispatcher.registerOnBackInvokedCallback(
        OnBackInvokedDispatcher.PRIORITY_DEFAULT
    ) {
        // Back is pressed... Finishing the activity
        finish()
    }
} else {
    onBackPressedDispatcher.addCallback(
        this, // lifecycle owner
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // Back is pressed... Finishing the activity
                finish()
            }
        })
}

UPDATE:

Thanks to @ianhanniballake comment; you can just use OnBackPressedDispatcher even in API level 33

The OnBackPressedDispatcher is already going to be using the Android T specific API internally when using Activity 1.6 ,

So, you can just do:

onBackPressedDispatcher.addCallback(
    this, // lifecycle owner
    object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            // Back is pressed... Finishing the activity
            finish()
        }
    })

Note that you shouldn't override the onBackPressed() as that will make the onBackPressedDispatcher callback not to fire; check this answer for clarifying that.

  • Related