I have upgraded targetSdkVersion
and compileSdkVersion
to 33
.
I am now getting a warning telling me that onBackPressed is deprecated.
I see suggestions to use android.window.OnBackInvokedCallback or androidx.activity.OnBackPressedCallback to handle back navigation instead. Can anyone can help me use the updated method?
Example
Use Case
I use if (isTaskRoot) {}
inside the onBackPressed() method to check whether the activity is the last one on the activity stack.
override fun onBackPressed() {
if (isTaskRoot) { // Check whether this activity is last on the activity stack. (Check whether this activity opened from a Push Notification.)
startActivity(Intent(mContext, Dashboard::class.java))
finish()
} else {
finishWithResultOK()
}
}
According your API level register:
onBackInvokedDispatcher.registerOnBackInvokedCallback
for API level 33+onBackPressedDispatcher
callback for backword compatibility "API level 13+"This requires to at least use
appcompat:1.6.0-alpha03
; the current is1.6.0-alpha04
:UPDATE:
Thanks to @ianhanniballake comment; you can just use
OnBackPressedDispatcher
even in API level 33+So, you can just do:
Note that you shouldn't override the
onBackPressed()
as that will make theonBackPressedDispatcher
callback not to fire; check this answer for clarifying that.