4

I am dealing with the following issue with Firemonkey (Delphi 10.4): When the Android OS will shut down and my app is still running, it does not trigger the OnCloseQuery, OnClose, and nor the OnDestroy events. Is there a way to detect or intercept the OS shutdown event? The same issue is presented when I kill the app with the square button (that is when I show the recently opened apps with the square button and I close the app that way).

Thank you in advance.

LUIS A. GAMA
  • 117
  • 6
  • Listening for the WillTerminate event works at least on Android - that's for when the *app* is about to terminate. Note that on Android when the app has reached this point, the app is *very* limited in what it can do. The [code here](https://github.com/DelphiWorlds/Kastri/blob/master/Core/DW.ServiceCommander.Android.pas) could be used as an example of how to listen for the event. I doubt that there's any reliable way from an app of detecting when the OS is about to shut down – Dave Nottage May 13 '21 at 06:07
  • Maybe [this](https://stackoverflow.com/questions/10448304/handling-phone-shutdown-event-in-android) or [this](https://stackoverflow.com/questions/21852882/how-to-detect-android-phone-is-being-turned-off) can give you helpful ideas. Neither is specifically for Delphi, but anyway... – Tom Brunberg May 13 '21 at 07:10
  • Thank you guys for your answers =) – LUIS A. GAMA May 13 '21 at 16:25

1 Answers1

4

I finally found a solution from a TMS customer (Ken Randall "Randall_Ken" Active Customer.)

uses FMX.Platform;

procedure TMyForm.FormCreate(Sender: TObject);
var
  AppEventSvc: IFMXApplicationEventService;
begin
  if TPlatformServices.Current.SupportsPlatformService
    (IFMXApplicationEventService, IInterface(AppEventSvc)) then
  begin
    AppEventSvc.SetApplicationEventHandler(AppEvent);
  end;
end;

function TMyForm.AppEvent(AAppEvent: TApplicationEvent;
AContext: TObject): Boolean;
begin
  if AAppEvent = TApplicationEvent.WillTerminate then
  begin
    // Do soomething
  end;
  Result := true;
end;
LUIS A. GAMA
  • 117
  • 6
  • Please note that you cannot rely on this message to be fired, at least on iOS. If the app enters the background, then it might be removed from memory by iOS to free up memory. In that situation you will not receive a terminate message. Therefore you must also handle the "entered background" message as if the app closes. – Hans May 14 '21 at 06:39