Delphi 10 Seattle Update1 如何停止主机应用程序的服务

Delphi 10 Seattle Update1 how can I stop service from host app

我使用 Delphi 10 Seattle update1 并且我有一个 android 服务,我从主机应用程序开始,但我不知道如何从主机应用程序停止该服务。谁能告诉我,好吗?

您正在使用 TLocalServiceConnection.StartService() 方法。 Embarcadero没有提供相应的TLocalServiceConnection.StopService()方法,所以你将不得不直接调用Android的Context.stopService()方法。

这是来自 $(BDS)\source\rtl\android\System.Android.Service.pasTLocalServiceConnection.startService() 的源代码:

class procedure TLocalServiceConnection.StartService(const AServiceName: string);
var
  LIntent: JIntent;
  LService: string;
begin
  LIntent := TJIntent.Create;
  LService := AServiceName;
  if not LService.StartsWith('com.embarcadero.services.') then
    LService := 'com.embarcadero.services.' + LService;
  LIntent.setClassName(TAndroidHelper.Context.getPackageName(), TAndroidHelper.StringToJString(LService));
  TAndroidHelper.Activity.startService(LIntent);
end;

您可以将 TAndroidHelper.Activity.startService() 替换为 TAndroidHelper.Activity.stopService():

var
  LIntent: JIntent;
begin
  LIntent := TJIntent.Create;
  LIntent.setClassName(TAndroidHelper.Context.getPackageName(), TAndroidHelper.StringToJString('com.embarcadero.services.LocationService'));
  TAndroidHelper.Activity.stopService(LIntent);
end;