Android Hard Back Button Tip

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

In this post hard back button refers to the Samsung physical button, and the gesture on the Pixel.

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

For example, here the TPictureView either asks the controller to go back to the MainView or forwards to show the selected picture:

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. The main view has the opportunity to do any processing here, or ignore the gesture if so desired. In my case, I simply send the application to the background:

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 )

Facebook photo

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

Connecting to %s