Activity.OnBackPressed Method

Definition

Called when the activity has detected the user's press of the back key.

[Android.Runtime.Register("onBackPressed", "()V", "GetOnBackPressedHandler")]
public virtual void OnBackPressed ();
[<Android.Runtime.Register("onBackPressed", "()V", "GetOnBackPressedHandler")>]
abstract member OnBackPressed : unit -> unit
override this.OnBackPressed : unit -> unit
Attributes

Remarks

Called when the activity has detected the user's press of the back key. The default implementation depends on the platform version:

<ul> <li>On platform versions prior to android.os.Build.VERSION_CODES#S, it finishes the current activity, but you can override this to do whatever you want.

<li>

Starting with platform version android.os.Build.VERSION_CODES#S, for activities that are the root activity of the task and also declare an android.content.IntentFilter with Intent#ACTION_MAIN and Intent#CATEGORY_LAUNCHER in the manifest, the current activity and its task will be moved to the back of the activity stack instead of being finished. Other activities will simply be finished.

<li>

If you target version android.os.Build.VERSION_CODES#S and override this method, we strongly recommend to call through to the superclass implementation after you finish handling navigation within the app.

<li>

If you target version android.os.Build.VERSION_CODES#TIRAMISU or later, you should not use this method but register an OnBackInvokedCallback on an OnBackInvokedDispatcher that you can retrieve using #getOnBackInvokedDispatcher(). You should also set android:enableOnBackInvokedCallback="true" in the application manifest.

Alternatively, you can use androidx.activity.ComponentActivity#getOnBackPressedDispatcher() for backward compatibility. </ul>

This member is deprecated. Use OnBackInvokedCallback or androidx.activity.OnBackPressedCallback to handle back navigation instead. <p> Starting from Android 13 (API level 33), back event handling is moving to an ahead-of-time model and Activity#onBackPressed() and KeyEvent#KEYCODE_BACK should not be used to handle back events (back gesture or back button click). Instead, an OnBackInvokedCallback should be registered using Activity#getOnBackInvokedDispatcher()OnBackInvokedDispatcher#registerOnBackInvokedCallback(int, OnBackInvokedCallback) .registerOnBackInvokedCallback(priority, callback).

Java documentation for android.app.Activity.onBackPressed().

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Applies to