在移动应用开发中,一个程序被切到后台,有的时候,我们需要保存下状态,然后以便在程序被操作系统在后台中止时,再次启动能够恢复原来的状态(比如 iOS 中,你的程序被切后台后,很可能由于某些原因(如内存不足)被操作系统中止)。要实现这个效果,您可以:
1、在主窗体的 OnCreate 事件中,检查 SaveState 的 Stream 的大小,如果不为0,代表你在上次切换到后台时,保存了状态信息,你需要做的就是从中恢复状态数据。然后再清除掉保存的状态文件,以避免下次启动时由于状态文件还存在,从而恢复成了错误的状态。
一个简单的示例函数,这里使用未加密的 QJSON 来保存数据状态:
procedure RestoreStates; var AJson: TQJson; AService: IFMXSaveStateService; begin SaveState.StoragePath := System.IOUtils.TPath.GetDocumentsPath + System.IOUtils.TPath.DirectorySeparatorChar;//指定状态文件保存目录 SaveState.Name := 'frmMain.States'; if SaveState.Stream.Size > 0 then begin AJson := TQJson.Create; try AJson.LoadFromStream(SaveState.Stream); ...//添加恢复代码 finally FreeAndNil(AJson); if TPlatformServices.Current.SupportsPlatformService (IFMXSaveStateService, AService) then // 删除临时文件 AService.SetBlock(SaveState.Name, nil); end; end; end;
2、在窗体的 OnSaveState 事件中,保存当前应用的状态:
procedure TfrmMain.FormSaveState(Sender: TObject); var AJson: TQJson; begin SaveState.Stream.Size := 0; if not ReadOnly then begin AJson := TQJson.Create; try ... 添加保存状态的代码 AJson.SaveToStream(SaveState.Stream); finally FreeAndNil(AJson); end; end; end;
好了,这样在程序启动时,就会恢复应用的状态,不怕应用被后台清理掉了。实际上,我们也可以不使用它的SaveState 接口,自己保存文件并恢复就好。注意这个文件如果放到了其它程序可见的目录下时,应该加密以避免隐私泄露。