Firemonkey 모바일 앱 라이프 사이클 이벤트 처리하기(앱 완전 구동 후 실행하기)
2015.04.09 20:28
앱이 실행 후 바로 수행해야 하는 초기화 작업을 FormCreate에서 하게되면 앱의 구동시간이 길어집니다.(FormShow 이벤트도 앱이 구동 중 발생됩니다.)
앱이 완전히 구동된 이후 초기화 작업을 실행하려면 아래와 같이 처리할 수 있습니다.
(interface uses 절에 FMX.Platform 추가)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | <p>unit Unit1;interfaceuses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Platform;type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); private { Private declarations } FInit: Boolean; procedure InitData; function HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; public { Public declarations } end;var Form1: TForm1;implementation{$R *.fmx}procedure TForm1.FormCreate(Sender: TObject);var EventService: IFMXApplicationEventService;begin FInit := False; if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, IInterface(EventService)) then EventService.SetApplicationEventHandler(HandleAppEvent) else InitData;end;function TForm1.HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;begin case AAppEvent of TApplicationEvent.FinishedLaunching, TApplicationEvent.BecameActive: InitData; end; Result := True;end;procedure TForm1.InitData;begin if FInit then Exit; // 데이터 및 컨트롤 초기화 FInit := True;end;end.</p> |
참고로 FinishedLaunching 이벤트가 iOS에서 발생하지 않습니다. 그래서 iOS의 경우 BecameActive 이벤트를 이용해 초기화 진행했습니다.
BecameActive 이벤트는 앱 활성화 될 때 마다 발생하기 때문에 중복방지 코드(if FIni then Exit;)를 추가했습니다.

타이머(TTimer)를 이용하는 방식도 활용하시기 바랍니다.
폼에 타이머를 하나 올리고, 타이머를 1회만 동작하도록 합니다.
(타이머는 폼이 완전구동이후 동작합니다.)
procedure TForm1.FormCreate(Sender: TObject);
begin
tmrInit.Enabled := True;
end;
procedure TForm1.tmrInitTimer(Sender: TObject);
begin
tmrInit.Enabled := False;
InitData;
end;