Android Application Events

Originally shared by Lars Fosdal

Android Application Events

There are a few differences between a Windows App and an Android App that puzzled me initially.  Why doesn’t my application get FocusChanged Activate/Deactivate or Close when switching between or terminating apps on Android?

Turns out that FireMonkey has extra trickery for that in FMX.Platform.

You need to hook your own event handler in.  

function TBasicAndroidForm.AppEventHandler(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;

begin

  Result := True;  // Does it matter what result you return?

  LogEvent(‘AppEvent ‘ + TRttiEnumerationType.GetName(AAppEvent));

end;

procedure TBasicAndroidForm.SetupAndroidEventHook;

var

  ApplicationEventService: IFMXApplicationEventService;

begin

  if TPlatformServices.Current

   .SupportsPlatformService(IFMXApplicationEventService, IInterface(ApplicationEventService))

    then ApplicationEventService.SetApplicationEventHandler(AppEventHandler);

end;

I’ve attached a small test project that show some of the events you get when you start the app.

Starting the app:

Create, Resize, Resize, Resize, Show, Activate, aeFinishedLaunching, and aeBecameActive.

The app is now up and running.

If I now pull down the Android system menu, I only get aeWillBecomeInactive.

 

If I close the system menu, I get aeBecameActive.

If I click the home button to get to the main Android navigator, I get aeWillBecomeInactive, aeEnteredBackground,  aeWillBecomeInactive. Why the double event? I don’t know.

Using the Android task switch, I bring the app back up on display, and get aeWillBecomeForeground, aeBecameActive.

Note that during this, I did NOT get the form events Show, Resize or Activate.

If you lock the Android device or open the task switcher, you get the same events as if you visited Home.

Note that if you leave your device inactive for a long time –  the App may actually fully terminate, leaving you with _aeWillBecomeInactive and aeEnteredBackground_ as key events for securing what appears as a persistent state for the user.  

If you don’t save your states here, you may not get another chance to do it.

#delphi   #android