Issue
I have upgraded targetSdkVersion and compileSdkVersion to 33.
Now getting warning onBackPressed is deprecated.
It is suggested to use use OnBackInvokedCallback or androidx.activity.OnBackPressedCallback to handle back navigation instead. Anyone can help me to use the updated method.
Example:
Use Case: I use if (isTaskRoot) {} inside onBackPressed(){} method to check activity is last on the activity-stack.
override fun onBackPressed() {
if (isTaskRoot) { // Check this activity is last on the activity-stack.(Check Whether This activity opened from Push-Notification)
startActivity(Intent(mContext, Dashboard::class.java))
finish()
} else {
finishWithResultOK()
}
}
Solution
According your API level register:
onBackInvokedDispatcher.registerOnBackInvokedCallbackfor API level 33+onBackPressedDispatchercallback 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.
Answered By - Zain

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.