Delphi 10.4.1,带计时器的 Android 应用程序中的服务

问题描述 投票:0回答:2

我发现在 Delphi 10.4.1 中,将 Timer 组件放在与多设备应用程序关联的服务的数据模块上,启动该服务后应用程序会立即关闭。

我认为这是一个错误,已在以后的版本中修复。

我需要在服务内保持一个运行周期,定期(每 2-3 小时)使用来自外部服务器的数据更新内部数据。

无法使用计时器,因此在我的例子中,要使用计时器,我想到了一个内部带有 while 循环的线程,它验证时间戳并每隔一定时间段执行所需的查询。

但不知道这样会不会消耗手机太多资源

您有什么建议吗?

android delphi service timer delphi-10.4-sydney
2个回答
0
投票

尝试使用原生 Android 计时器,而不是 Delphi TTimer。 DelphiWorlds KastiFree 附带了一个源代码,我可以成功地独立使用它,而无需使用此包的其余部分。 在这里找到单位: Android定时器


0
投票

创建一个在后台运行并每 1 秒(或所需的秒数)执行一次的线程,并在睡眠后执行该过程。

在表单的私有变量中声明:

MyThread: TThread;

创建启动线程的过程:

procedure TFrmPrincipal.StartThread;
begin
   MyThread := TThread.CreateAnonymousThread(
   procedure
   begin
     while not MyThread.CheckTerminated do
     begin
       // progressing every 1 second (or the desired number of seconds)
       Sleep(1000);

       // here execute commands that do not interact with the screen
       // ....

       TThread.Synchronize(TThread.currentthread,
       procedure
       begin
         // here execute commands that do interact with the screen
         // ....
       end);
     end;
   end);

   MyThread.OnTerminate := ThreadTerminate;
   MyThread.FreeOnTerminate := False;
   MyThread.Start;
end;

为线程编写 onTerminate,以便捕获任何错误:

procedure TFrmPrincipal.ThreadTerminate(Sender: TObject);
begin
   if Sender is TThread then
   begin
     if Assigned(TThread(Sender).FatalException) then
     begin
       showmessage(Exception(TThread(Sender).FatalException).Message);
       Exit;
     end;
   end;
end;

在表单中close write以避免内存泄漏:

if Assigned(MyThread) then
   begin
     MyThread.Terminate;
     FreeAndNil(MyThread);
   end;

在表单中显示启动MyThread:

StartThread;
© www.soinside.com 2019 - 2024. All rights reserved.