Android Hard Back Button Tip

Some Android phones have a hard back button, like the Samsung Galaxy 7 or Note 9. Others like the Pixel 4a use a short gesture from the left or right edge of the phone to trigger the effect of a hard back button press. If you don’t handle this event, your application will automatically go into the background. Fortunately, this is easy to manage.

The recommended architecture for a Delphi mobile application is to use one form which hosts multiple frames representing the individual views.

I use an application controller to manage the views, and to simplify navigation:

To handle the hard back button press we need to manage the FormKeyUp event in the main form:

Note: we set the key to 0 so it won’t be detected by a default handler.

We pass the event to the controller who in turn delegates to the currently docked view:

In the pictures view shown earlier, the handler simply navigates back to the main view. However, if the event occurs in the main view, it sends the application to the background:

A nice confluence is the controller registers itself with the app bar to handle the soft back button:

Using the following code:

  AppBar.OnBackPressed := OnBackButtonPressed;

So whether the source is a hard button press, or the app bar back button press, the same event handler is called on the views via the controller’s delegation.

I hope this tip helps.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s