android - When the application is closed, the Android Local service was stopped
问题描述
I'm using Delphi 10.3 for developing android application and I have implemented Service to retrieve the data from Server. The thread was running properly but it closes when the app is closed. I have used the following code to run the service:
DMService.StartCommand();
begin
AddLog; //Log
SampleThread := TThread.Create;
Result := TJService.JavaClass.START_REDELIVER_INTENT;
end;
The same code worked fine in Delphi 10.1 (without mentioning the Android 26 as target version).
Also I have tried using TTask but still the problem does not resolves.
Also I have tried Result := TJService.JavaClass.START_STICKY;
, but still the service closes.
And after several analysis, I have analyzed after closing the host application the service, the Service starts again and the thread/Task initiated and the service was destroyed.
Should I need to enable any special permission or while creating should I need to add more code. Currently, I'm using the following code for initiating the service from the host application:
FLocalServiceConnection := TLocalServiceConnection.Create;
FLocalServiceConnection.StartService('SCommuteSupervisorNotificationService');
Please help me to resolve this issue to run the service after the host app closes.
解决方案
这段代码对我有用
procedure TDM.StartForeground;
var
LBuilder: JNotificationCompat_Builder;
begin
try
//if FIsForeground or not TAndroidHelperEx.CheckBuildAndTarget(26) then
//Exit; // <======
LBuilder := TJNotificationCompat_Builder.JavaClass.init(TAndroidHelper.Context);
LBuilder.setAutoCancel(True);
LBuilder.setContentTitle(StrToJCharSequence('Sample'));
LBuilder.setContentText(StrToJCharSequence('Monitoring location changes'));
LBuilder.setSmallIcon(TAndroidHelper.Context.getApplicationInfo.icon);
LBuilder.setTicker(StrToJCharSequence('Sample 2'));
TJService.Wrap(System.JavaContext).startForeground(3987, LBuilder.build);
except
end;
end;
function TDM.AndroidServiceStartCommand(const Sender: TObject;
const Intent: JIntent; Flags, StartId: Integer): Integer;
begin
StartForeground;
Result := TJService.JavaClass.START_STICKY;
end;
推荐阅读
- javascript - 如何在从函数返回的只读字段中显示值
- html - 使文本和href对齐完美需要适当的css
- php - Laravel Env 文件:如何添加包含空格的文件路径
- amazon-web-services - 反正有没有在红移表中只保留一周的数据
- javascript - 双向视频会议webrtc的问题
- spring-boot - 迁移 spring-boot 1 到 spring-boot 2.2.5,使用 JSP
- java - PreAuthorize 仅适用于 GET 请求
- asp.net-core - 在 ASP.NET Core 3.1 中找不到 Sustainsys /Saml2/Acs url
- node.js - 是否可以将 Sonarqube 集成到 nodejs 项目的 azure devops 管道中?
- db2 - 使用 ODBC 在 ACE 11 ESQL 中访问 DB2 数据库