onBackPressed() is deprecated

Jyotishgher Astrology
By -
1 minute read
0

 OnBackPressedDispatcher in Android

While Targeting Android 13 , OnbackPressed Override Function is deprecated. Usually, we used to intercept on backpress and add animations. we all know, this onBackPressed function will call as soon as the Back button is clicked (Hardware) or back pressed from the navigation gesture. But, now it’s time to change/move.

OnBackPressedDispatcher in Android

Traditionally, developers would override the onBackPressed() method in their activities to customize back navigation. However, this method has been deprecated as of Android 13, in favor of a more versatile and robust approach involving OnBackPressedDispatcher

Since onBackPressed() is deprecated, you should use OnBackPressedDispatcher in your activity. Here’s how to properly handle the back button press in newer Android versions:

Close Only the Current Activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            finish(); // Closes the current activity
        }
    });
}

Exit the App Completely

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            finishAffinity(); // Exits the app
        }
    });
}

This ensures smooth back navigation while adhering to Android’s latest guidelines. Let me know if you need further improvements!  In Android 13, we have a new Preview feature called, “Predictive back gesture.” Currently, it’s not available for end-Users. Because of this feature, they deprecated the onBackPressed Function in Android 13. So we are going to migrate and make our apps to get ready for Android 13’s predictive back gesture.

Tags:

Post a Comment

0Comments

Post a Comment (0)