4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Delphi] Android の Back ボタンでアプリを終わらせない方法

Last updated at Posted at 2021-01-05

Delphi 製 Android アプリ

Delphi で Android のアプリを作ると「バックキー」でアプリ終わっちゃうんだよね!

Android 使いなら解ってくれると思うけど、ホームキーはあんまり押さないで、バックキーを連打するじゃないですか!え、しませんか!?
で、バックキーを連打で終わらせると Delphi のアプリ、次に起動した時またスプラッシュから~!?となり割とイラッとするので、僕が作るアプリは基本終わらないようにしています。

終わらせないコード

この2つを合せて↓下記の様にします。

uses
  Androidapi.Helpers;

procedure TForm1.FormKeyUp(
  Sender: TObject;
  var Key: Word;
  var KeyChar: Char;
  Shift: TShiftState);
begin
  {$IFDEF ANDROID}
  if Key = vkHardwareBack then // Android バックキーの仮想キーコード
  begin
    // Key, KeyChar を 0 にしないとデフォルトの動作が呼ばれ Activity が閉じてしまう
    Key := 0;
    KeyChar := #0; 
    // アプリを裏に回す
    TAndroidHelper.Activity.MoveTaskToBack(True);
  end;
  {$ENDIF}
end;

実質たった8行だけで Activity が閉じなくなるので常に書いておくことをオススメします。
これで、アプリがメモリにある間は起動しても前回の続きから表示されます。

戻ってきたとき再描画させる

ただ、これだけだとたまに戻ってきたときにアプリの内容が表示されない(真っ白の画面が表示されるような状態)場合があります。
これを防ぐためには IFMXApplicationEventService を使います。
TForm.OnCreate などで設定しておくと良さそうです。

uses
  FMX.Platform;

procedure TForm1.FormCreate(Sender: TObject);
begin
  var Service: IFMXApplicationEventService;
  if
    TPlatformServices.Current.SupportsPlatformService(
      IFMXApplicationEventService,
      Service
    )
  then
    // 下の AppEvent を登録
    Service.SetApplicationEventHandler(AppEvent); 
end;

function TForm1.AppEvent(
  iAppEvent: TApplicationEvent;
  iContext: TObject): Boolean;
begin
  Result := False;

  case iAppEvent of
    // これからアクティブになるよというイベント
    TApplicationEvent.BecameActive: 
    begin
      // Form の Invalidate メソッドを呼んで再描画をうながす
      Invalidate; 
    end;
  end;

最後に

Activity#moveTaskToBack() と Activity#finish() のどちらをバックキーのデフォルトの動作にするかプロパティで選べるようになってたら良いのになあ(Android 単体の話だから無理かな)

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?