Haifisch
Haifisch

Reputation: 909

Send Android app to background with Firemonkey

With Delphi 11 I'm doing a Android app.

I have a main form (TMainForm) with a layout where I pop/push some views.

When user touch back button (vkHardwareBack) I cancel the key and manually pop view.

if Key = vkHardwareBack then begin
  Key := 0;
  Scenes.Pop;
end;

The problem, is when the stack scene contain only 1 view, the back button delete it and the user see the empty main form, when he do back again, the app go to background.

If I let Firemonkey do the back action

if (Key = vkHardwareBack) and (Scenes.Count > 1) then begin
  Key := 0;
  Scenes.Pop;
end;

I get the same result, Firemonkey pop the last scene and show the empty form.

Does it exist something to sent app to background manually ? like the code below ?

if Key = vkHardwareBack then begin
  Key := 0;
  if Scenes.Count > 1 then
    Scenes.Pop
  else 
    SendAppToBackground;
end;

Upvotes: 0

Views: 759

Answers (1)

Dave Nottage
Dave Nottage

Reputation: 3602

This code should do what you want:

uses
  Androidapi.Helpers, Androidapi.JNI.GraphicsContentViewText;

procedure SendAppToBackground;
var
  LIntent: JIntent;
begin
  LIntent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_MAIN);
  LIntent.addCategory(TJIntent.JavaClass.CATEGORY_HOME);
  LIntent.setFlags(TJIntent.JavaClass.FLAG_ACTIVITY_NEW_TASK);
  TAndroidHelper.Context.startActivity(LIntent);
end;

Based on this answer.

EDIT:

My memory is defective because I came up with this 2 years ago:

uses
  Androidapi.Helpers;

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
  if key = vkHardwareBack then
  begin
    Key := 0;
    TAndroidHelper.Activity.moveTaskToBack(True);
  end;
end;

Having said that, this solution might not go to the Home screen

Upvotes: 1

Related Questions