androidandroid-api-levels

Android - Back Button behavior difference between API 35 and API 36


I have a very simple piece of code in an app that has been running fine for YEARS. I am updating to API 36 using Android Studio. I tested in a virtual Pixel 9 API 36 today and noticed that the BACK button behavior seems different from API 35 and earlier.

The code:

override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
    if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
        webView.goBack()
        return true
    }
    // If it wasn't the Back key or there's no webpage history, bubble up to the default
    // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event)
}

The behavior in API 35 and previous is similar to a back press in a browser, you go back a page in the webview or the app closes if you are at the top level.

In API 36, you still go back a page but then the app minimises into the background (it does not close) and you end up at the main screen of the OS / device.

I have side by side tested in Android Studio with a Pixel 9 API 36 emulator device and with a Pixel 9 API 35 emulator device with identical code (same project, two AVDs side by side) and the effect is reproducible.

Any thoughts on how to overcome this behavior in API 36 without breaking API 35 and previous?

If I compile to API 35, it works as I expect (back button works to go back a page and leaves app open on device) on both AVDs (both Pixel 9 API 35 and API 36) but as I said, trying to update to the latest and greatest...


Solution

  • API Level 36 (Android 16) changes user experience of back button as described in Migration or opt-out required for predictive back.
    You can either implement new predictive behavior or opt-out by setting in Android Manifest the attribute android:enableOnBackInvokedCallback to false. Note that the opt-out will become ineffective in a later API release.