The Back Button

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 on the main activity.

If you ignore this event, your application will automatically go into the background, potentially losing state.

Fortunately, this is easy to manage.

Handling the Button

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

procedure TMainForm.FormKeyUp(
        Sender: TObject; 
        var Key: Word; 
        var KeyChar: Char;
        Shift: TShiftState);
begin
    if Key = vkHardwareBack then
    begin
        // Save State
        // Allow application to go into the background
    end;
end;

It is good practice to respect the user's intentions, but if you need to prevent this action, clear the Key:

procedure TMainForm.FormKeyUp(
        Sender: TObject; 
        var Key: Word; 
        var KeyChar: Char; 
        Shift: TShiftState);
begin
    if Key = vkHardwareBack then
    begin
        // prevent the gesture, application will ignore the user request
        Key := 0;
        exit;
    end;
end;