I have upgraded targetSdkVersion
and compileSdkVersion
to 33
.
CodePudding user response:
You can use the OnBackInvokedCallback
as described in the documentation and follow this guide here to update your code
CodePudding user response:
According your API level register:
onBackInvokedDispatcher.registerOnBackInvokedCallback
for API level 33onBackPressedDispatcher
callback for backword compatibility "API level 13 "
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.