One thing that I’ve wanted to try for quite a while is doing something when an app gets put in the background (user hits the home button for example). An example of this is a game that my kids play - when they leave the game, the character yells out something like "Don’t leave!", "Come back!", "Hope you enjoy your day without me!" and other random fun stuff.
Sometimes it also schedules a notification to fire at a later date. Let’s say the kids forget to play the game for a few days… All of a sudden out of nowhere the iPad will scream at you "Come back and play NOW! I’m bored!"
How is this done? Let’s not waste anymore time… Here is the complete form source code for the simplest case - scheduling a notification upon entering the background.
unit Unit1;
interface
uses
System.SysUtils, System.Classes, FMX.Forms, FMX.Platform;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function AppEvent(AAppEvent: TApplicationEvent; AContext: TObject) : Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
FMX.Notification;
procedure SendNotification;
var
NotificationService: IFMXNotificationCenter;
Notification: TNotification;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXNotificationCenter) then
NotificationService := TPlatformServices.Current.GetPlatformService(IFMXNotificationCenter) as IFMXNotificationCenter;
if Assigned(NotificationService) then begin
Notification := TNotification.Create;
try
Notification.Name := 'MyLocalNotification';
Notification.AlertBody := 'Hello from the Delphi XE4 iOS app that you used 5 seconds ago!';
Notification.FireDate := Now + EncodeTime(0,0,5,0);
NotificationService.ScheduleNotification(Notification);
finally
Notification.Free;
end;
end
end;
function TForm1.AppEvent(AAppEvent: TApplicationEvent; AContext: TObject) : Boolean;
begin
if AAppEvent = TApplicationEvent.aeEnteredBackground then
SendNotification;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
AppEventSvc: IFMXApplicationEventService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, IInterface(AppEventSvc)) then
AppEventSvc.SetApplicationEventHandler(AppEvent);
end;
end.
The main things that we do in this code are:
1. Hook up the Application Event Handler on OnCreate of our form
2. Schedule a notication if the event received is aeEnteredBackground
The rest is handled by iOS for us.
Special thanks to Darren Kosinski who shared one of his test examples on how to handle iOS application events!
Share This | Email this page to a friend